Home > Web Front-end > JS Tutorial > How to Convert a Comma-Separated String to an Array in JavaScript?

How to Convert a Comma-Separated String to an Array in JavaScript?

Susan Sarandon
Release: 2024-11-07 20:39:03
Original
826 people have browsed it

How to Convert a Comma-Separated String to an Array in JavaScript?

Converting Comma-Separated String to Array in JavaScript

When attempting to convert a comma-separated string to a JavaScript array using the code snippet provided, the resulting array remains as a string rather than an array of separate elements.

To effectively achieve this conversion, JSON.parse() can be utilized. By wrapping the string in square brackets, JSON.parse() interprets it as an array.

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

This results in an array of numbers:

[0, 1]
Copy after login

Alternatively, .split() can be employed to create an array of strings.

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

Output:

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

It's important to note that JSON.parse() restricts the data types to supported ones. If values like undefined or functions are required, eval() or a JavaScript parser will be necessary.

For instances where .split() is used and an array of numbers is desired, Array.prototype.map can be applied, although it might require a shim for IE8 and below or a traditional loop.

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

The above is the detailed content of How to Convert a Comma-Separated String to an Array 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template