Home >Web Front-end >Front-end Q&A >How to convert string to array in javascript
3 conversion methods: 1. Use split() to split a given string into a string array, the syntax is "str.split (separator, maximum length of array)"; 2. Use expansion Operator "..." can iterate a string object and convert it into a character array, the syntax is "[...str]"; 3. Use Array.from() to convert the string into an array, the syntax is " Array.from(str)".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
3 ways to convert strings to arrays in javascript
Use split()
Use the spread operator "..."
Use Array.from()
Method 1: Use the split() method for conversion
The split() method is used to split the given string into an array of strings; the method is to use the specified delimiter provided in the parameter. Separate it into substrings, and then pass them into the array as elements one by one.
Syntax:
str.split(separator, limit)
Parameters:
separator: Optional. A string or regular expression to split the string Object from where specified by this parameter.
#limit: Optional. This parameter specifies the maximum length of the returned array. If this parameter is set, no more substrings will be returned than the array specified by this parameter. If this parameter is not set, the entire string will be split regardless of its length.
Example 1:
var str="Welcome to here !"; var n=str.split(""); console.log(n);
Example 2:
var str="Welcome to here !"; var n=str.split(" "); console.log(n);
Example 3:
var str="Welcome to here !"; var n=str.split("e"); console.log(n);
##Method 2: Use the spread operator "...”
##Expand operator
is introduced in ES6, which expands the iterable object into its separate elements. The so-called iterable object is any object that can Objects traversed using a for of loop. String is also an iterable object, so you can also use the spread operator
to convert it into a character array <pre class="brush:js;toolbar:false">const title = "china";
const charts = [...title];
console.log(charts); // [ &#39;c&#39;, &#39;h&#39;, &#39;i&#39;, &#39;n&#39;, &#39;a&#39; ]</pre>
Then you can simply intercept the string, as follows:
const title = "china"; const short = [...title]; short.length = 2; console.log(short.join("")); // ch
Method 3: Use the Array.from() method to convert The Array.from() method is a built-in function in JavaScript that creates a new array instance from the given array. For strings, each alphabet of the string is converted to an element of the new array instance; for integer values, the new array instance simple takes the elements of the given array.
Grammar:
Array.from(str)
Example:
var str="Welcome to here !"; var n=Array.from(str); console.log(n);
##[Recommended learning: javascript advanced tutorial
]The above is the detailed content of How to convert string to array in javascript. For more information, please follow other related articles on the PHP Chinese website!