Home > Web Front-end > JS Tutorial > How to Convert Comma-Delimited Strings to Arrays in JavaScript?

How to Convert Comma-Delimited Strings to Arrays in JavaScript?

DDD
Release: 2024-11-06 17:42:02
Original
434 people have browsed it

How to Convert Comma-Delimited Strings to Arrays in JavaScript?

Converting Comma-Delimited Strings to Arrays in JavaScript

While attempting to convert a comma-separated string into a JavaScript array, you've noticed that the resulting array contains the entire string rather than the individual elements. To achieve the desired array format, consider the following solution:

Solution:

To convert a comma-separated string into an array of numbers, use JSON.parse as follows:

var array = JSON.parse("[" + string + "]");
Copy after login

This approach returns an array of numbers:

[0, 1]
Copy after login

Alternatively, using .split() will result in an array of strings:

["0", "1"]
Copy after login

Limitations:

JSON.parse has limitations when handling data types. If you require values like undefined or functions, use eval() or a JavaScript parser.

Additional Notes:

If you prefer to use .split() and obtain an array of numbers, you can employ Array.prototype.map to convert string elements to numbers. For compatibility with IE8 and earlier, you may need to create a shim or use a traditional loop:

var array = string.split(",").map(Number);
Copy after login

The above is the detailed content of How to Convert Comma-Delimited Strings to Arrays in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template