Cut strings into arrays/concatenate arrays into strings in JS

1. Cut string into array

Function method used: split()

(1) Grammar format:

let 数组变量 = 字符串.split(所选分隔符);

The selected delimiter is enclosed in double quotes ("") or single quotes ('');
the generated array will be stored in the array variable defined previously.

(2) Sample:

JS code:

var string = "元素一 元素二 元素三 元素四";
var array = string.split(" ")//使用空格作为分隔符
console.log(array);//打印生成的数组变量

operation result:

[ '元素一', '元素二', '元素三', '元素四' ]

(3) Other usages:

①When the selected delimiter is empty, the returned array will split each character:

JS code:

var string = "元素一 元素二 元素三 元素四";
var array = string.split("")//使用空分隔符
console.log(array);//打印生成的数组变量

operation result:

[
  '元', '素', '一', ' ',
  '元', '素', '二', ' ',
  '元', '素', '三', ' ',
  '元', '素', '四'
]
②If the delimiter is empty and the string is empty, an empty array is returned:

JS code:

var string = "";
var array = string.split("")//使用空分隔符
console.log(array);//打印生成的数组变量

operation result:

[]
③ Without delimiter, an array with a length of 1 and the content of the string itself will be returned:

JS code:

var string = "元素一 元素二 元素三 元素四";
var array = string.split()//不带分隔符
console.log(array);//打印生成的数组变量

operation result:

[ '元素一 元素二 元素三 元素四' ]
④Add the optional parameter limit to limit the length of cutting
string.split(splitter, limit);

Usage:
JS code:

var string = "元素一 元素二 元素三 元素四";
var array = string.split(" ", 3);//带分隔符、限定长度值
console.log(array);//打印生成的数组变量

operation result:

[ '元素一', '元素二', '元素三' ]
⑤Use regular expressions as delimiters

Usage:
JS code:

var string = "元素一?元素二!元素三.元素四";
var array = string.split(/[?,!,.]/);//正则分隔符
console.log(array);//打印生成的数组变量

operation result:

[ '元素一', '元素二', '元素三', '元素四' ]

2. Concatenate arrays into strings

Function method used: join()

(1) Grammar format:

let 数组变量 = 字符串.join(所选分隔符);

Like the split syntax, it will concatenate the arrays with the selected delimiter.

(2) Sample:

JS code:

var array = [ '元素一', '元素二', '元素三', '元素四' ];
var string = array .join(",")//使用空格作为分隔符
console.log(string);//打印生成的字符串

operation result:

元素一,元素二,元素三,元素四

3. Postscript

In fact, there are other ways to concatenate arrays into strings, but they are not better helpful for my work and study operations, so I will only write a few words here:

1. You can use a for loop to traverse and add up using the plus sign (+);

2. Use the function method toString() to connect the array into a string, and use commas (,) to connect each element in the array;

3. The function method toLocalString() method can connect the generated strings using the delimiters specific to the user's region to form a string.

There are other ways to convert string to array:

Since the string can be accessed directly based on the index, you can use a for loop to traverse and cut according to this principle:

string[num]

Guess you like

Origin blog.csdn.net/weixin_47278656/article/details/129951150