Detailed explanation of the split method of String in JavaScript

String.prototype.split()

The String.prototype.split() method splits a string object into a string array through the parameter symbol passed in. The parameter symbol passed in determines where the string is split.

var str = 'The quick brown fox jumps over the lazy dog.';

var words = str.split(' ');
console.log(words[3]);
// 输出: "fox"

var chars = str.split('');
console.log(chars[8]);
// 输出: "k"

var strCopy = str.split();
console.log(strCopy);
// 输出数组: ["The quick brown fox jumps over the lazy dog."]

grammar

str.split([separator[, limit]])

Notice!
If an empty string str.split("") is passed in when the split() function is called, only the string belonging to the UTF-16 character encoding can be split into single characters at this time, and if the string contains UTF- Characters other than 16, such as unicode characters or some rare words, cannot separate characters correctly. If you need to split unicode characters, you need to use regular expressions.

"hello".split("");
//["h", "e", "l", "l", "o"]

“????” .split("");
// ["�", "�", "�", "�", "�", "�", "�", "�"]
//因为部分unicode字符在js中用两个字码表示

"????".split(/(?=.)/us);
//["?", "?", "?", "?"]
//?=表示“向前查找”或“先行断言”。
//us是ES6新增的正则修饰符,u-支持unicode字码,s-代表.可以匹配任意字符包括换行

parameter

separator | optional
This parameter specifies where to split the string. The separator parameter can be a string or a regular expression. If the separator is a string, the separator string must be completely matched before the split is performed. If the separator parameter is not passed or the separator parameter is not matched in the called string, the return value will be an array containing the entire called string. If the separator parameter is an empty string, the split() function will split the called string into an array of characters.
limit | The optional
limit parameter is an integer that determines the number of splits for the split() function. If the limit parameter exists, the array length of the returned array will be less than or equal to limit. If there are still unsplit strings during splitting, but the length of the array has reached the limit value, then the remaining strings will be discarded and will not be returned in the result.

return value

The called string will be split every time the separator appears, and finally assembled into a string array and returned.

describe

When the function is executed, the called string will remove the same part as the separator parameter, and return the substring before and after the removed part as an array. If the separator parameter is not passed (undefined) or not matched, the returned array will contain an entire called string. If separator is an empty string, the called string will be split into an array of characters. If separator is matched at the beginning, end, or both of the called string, the returned array is filled with an empty string at the head, end, or both. If separator is equal to the entire called string, the returned array will contain two empty strings.
If the separator is a regular expression containing a capture group, then every time the separator is matched, the capture group in it will be additionally filled into the return array and returned, that is to say, the capture group will not be removed, but will be used as a separate An array of items is returned.

Notice!

  • If the separator passes in an array, the array will be coerced into a string and String(separator) will be executed.
  • If the called string is an empty string, but the separator is not an empty string, the split() function will return an array containing an empty string; if both the called string and the separator are empty strings, split( ) function returns an empty array.

example

Use the String.prototype.split() function

The following sample program shows the general usage of the split() function, and prints out the relevant information when calling in splitString:

function splitString(stringToSplit, separator) {
  var arrayOfStrings = stringToSplit.split(separator);

  console.log('The original string is: "' + stringToSplit + '"');
  console.log('The separator is: "' + separator + '"');
  console.log('The array has ' + arrayOfStrings.length + ' elements: ' + arrayOfStrings.join(' / '));
}

var tempestString = 'Oh brave new world that has such people in it.';
var monthString = 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec';

var space = ' ';
var comma = ',';

splitString(tempestString, space);
splitString(tempestString);
splitString(monthString, comma);

The program output is as follows:

The original string is: "Oh brave new world that has such people in it."
The separator is: " "
The array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it.

The original string is: "Oh brave new world that has such people in it."
The separator is: "undefined"
The array has 1 elements: Oh brave new world that has such people in it.

The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"
The separator is: ","
The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec

remove spaces from a string

In the following example, the split() function will match a regular expression that starts with any number of spaces, followed by a semicolon or ends with a string, followed by an arbitrary space. When this match is found, remove the entire match:

var names = 'Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ';

console.log(names);

var re = /\s*(?:;|$)\s*/;
var nameList = names.split(re);

console.log(nameList);

Analyze the regular expression, \s* represents any number of spaces; (?:;| ) is a capture group, but ? : represents non-acquisition, so this capture group will eventually be removed. In the capture group; ∣ ) is a capture group, but ?: means non-acquisition, so this capture group will eventually be removed. in capture group;|) is a capturing group , but the ?:Indicates non- acquisition , so this capturing group will eventually be removed . in the capture group ; indicates a semicolon or the end of a string. The final program output is as follows:

Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand 
[ "Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand", "" ]

Returns a length-limited result

In the following example, 3 is passed as the limit parameter in the split() function:

var myString = 'Hello World. How are you doing?';
var splits = myString.split(' ', 3);

console.log(splits);

The final output is as follows:

["Hello", "World.", "How"]

Use the capture group function of regular expressions to save part of the separator content

If separator is a regular expression and contains a capture group, then the capture group will be returned in the result:

var myString = 'Hello 1 word. Sentence number 2.';
var splits = myString.split(/(\d)/);

console.log(splits);

The capture group in the regular expression will appear as a single array item in the return value:

[ "Hello ", "1", " word. Sentence number ", "2", "." ]

Pass in an array to split

If the separator is an array, the split() function will first execute String(separator) to convert it into a string:

var myString = 'this|is|a|Test';
var splits = myString.split(['|']);

console.log(splits); //["this", "is", "a", "Test"]

var myString = 'ca,bc,a,bca,bca,bc';

var splits = myString.split(['a','b']); 
// myString.split(['a','b']) 等同于执行 myString.split(String(['a','b'])) 

console.log(splits);  //["c", "c,", "c", "c", "c"]

Reverse a string using the split() function

Note that this method is not applicable in all cases, and there are problems with unicode character sets:

var str = 'asdfghjkl';
var strReverse = str.split('').reverse().join(''); // 'lkjhgfdsa'
// split() 返回的数组可以正好调用reverse()和join()

var str = 'résumé';
var strReverse = str.split(/(?:)/u).reverse().join('');
// 输出 "́emuśer"。注意这里的结果已经和输入的字符串发生了一些变化

If you want to reverse a string containing a Unicode character set, you still need to check the character code and then reverse it, such as the small plug-in esrever .

Guess you like

Origin blog.csdn.net/yuhk231/article/details/88224446