Method: 1. Use the split() method to split the given string str into a string array. The syntax is "str.split(separator)", and the separator specifies the place to split; 2. Use Array .from() method, each letter of the string is converted into an element of a new array instance.
Method to convert string to array in JavaScript
Method 1: Use the split() method
The split() method is used to split the given string into a string array. This method is to separate it into sub-strings using the specified delimiter provided in the parameter. String.
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);
Output:
Example 2:
var str="Welcome to here !"; var n=str.split(" "); console.log(n);
Output:
Method 2: Use Array.from() method
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.
Syntax:
Array.from(str)
Example:
var str="Welcome to here !"; var n=Array.from(str); console.log(n);
Output:
Related free learning recommendations:js video tutorial
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!