How does js convert a string to an array? String array conversion

Method 1: Use the split() method

The split() method is used to split the given string into an array of strings by separating it into substrings using the specified delimiter provided in the parameter.

str.split(separator, limit)

parameter:

  • separator is optional. A string or regular expression to split the string Object from where specified by this parameter.
  • limit is 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:
insert image description here

Example 2:

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

output:
insert image description here

Method 2: Use the Array.from() method

Array.from() method is an inbuilt function in javascript which 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 an element of the given array.

Syntax: Syntax:

Array.from(str)

Example:

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

output:
insert image description here

array to string

grammar:

let arr=['1','2','3']
arr.toString()
console.log(arr)//'1,2,3'

Welcome everyone to like and collect! ! !

Guess you like

Origin blog.csdn.net/weixin_45449504/article/details/121747405
Recommended