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

How to convert string to array in js?

青灯夜游
Release: 2020-10-23 11:22:44
Original
126930 people have browsed it

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.

How to convert string to array in js?

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)
Copy after login

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);
Copy after login

Output:

How to convert string to array in js?

Example 2:

var str="Welcome to here !";
var n=str.split(" ");
console.log(n);
Copy after login

Output:

How to convert string to array in js?

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)
Copy after login

Example:

var str="Welcome to here !";
var n=Array.from(str);
console.log(n);
Copy after login

Output:

How to convert string to array in js?

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!

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!