Home >Web Front-end >JS Tutorial >How to convert string to array in js

How to convert string to array in js

下次还敢
下次还敢Original
2024-05-06 11:24:16503browse

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>

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>

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>

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>

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!

Statement:
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
Previous article:How to use splite in jsNext article:How to use splite in js