Home > Web Front-end > JS Tutorial > body text

How to convert string to array in js

下次还敢
Release: 2024-05-06 11:24:16
Original
425 people have browsed it

In JavaScript, you can use the following methods to convert a string into an array: use the spread operator to extract each element; use the Array.from() method to convert directly; use the split() method to split by delimiter; Use the match() method to match alphabetic words by a regular expression.

How to convert string to array in js

Method to convert a string into an array in JavaScript

In JavaScript, a string is a primitive type, whereas an array is an object. To convert a string to an array, you can use the following method:

1. Use the spread operator

spread operator (...) to spread the iterable object ( Each element in a string) is extracted into an array. For example:

<code class="js">const str = "Hello World";
const arr = [...str];
console.log(arr);  // 输出:["H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"]</code>
Copy after login

2. Use the Array.from() method

The Array.from() method converts an iterable object into an array. For example:

<code class="js">const str = "Hello World";
const arr = Array.from(str);
console.log(arr);  // 输出:["H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"]</code>
Copy after login

3. Use the split() method

split() method to use the specified character or regular expression as the delimiter to split the string into one array. For example:

<code class="js">const str = "Hello World";
const arr = str.split(""); // 以每个字符为分隔符
console.log(arr);  // 输出:["H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"]

const arr2 = str.split(" "); // 以空格为分隔符
console.log(arr2); // 输出:["Hello", "World"]</code>
Copy after login

4. Use the match() method

The match() method uses a regular expression to match the pattern in the string and returns a string containing the matched items. array. For example:

<code class="js">const str = "Hello World";
const arr = str.match(/[a-zA-Z]+/g); // 匹配所有字母单词
console.log(arr);  // 输出:["Hello", "World"]</code>
Copy after login

The above is the detailed content of How to convert string to array in js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!