Split() Detailed Explanation

Requirement: js takes out each element according to the comma in the string and puts it in the array

split()The method splits a String object into an array  of substrings using the specified delimiter string , and uses a specified split string to determine the position of each split.

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

const words = str.split(' ');
console.log(words[3]);
// Expected output: "fox"

const chars = str.split('');
console.log(chars[8]);
// Expected output: "k"

const strCopy = str.split();
console.log(strCopy);
// Expected output: Array ["The quick brown fox jumps over the lazy dog."]

grammar

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

Warning:  If an empty string (") is used as the delimiter, the string is not between each user-perceived character (graphic veneer cluster), nor between each Unicode character (code point), but between between each UTF-16 code unit. This destroys surrogate pairs. See also how do you get a string to a character array in javascript

parameter

separator

Specifies a string representing the point at which each split should occur. separator Can be a string or regular expression . If the plain text delimiter contains more than one character, the whole string must be found to represent the split point. If the delimiter is omitted or present in str, the returned array contains one element consisting of the entire string. If delimiter is the empty string, str is returned as an array of each character in the original string.

limit

An integer limiting the number of splits returned. When this parameter is provided, the split method splits the string at each occurrence of the specified delimiter, but stops when a limit entry has been placed into the array. If the end of the string is reached before the specified limit is reached, it may still contain fewer entries than the limit. The remaining text is not returned in the new array.

return value

Returns an Array of the source string separated by the position of the delimiter 

describe

When a delimiter is found, it is removed from the string and an array of substrings is returned. If no delimiter is found or omitted, the array contains one element consisting of the entire string. If delimiter is the empty string, convert str to a character array. If the delimiter appears at the beginning or end of the string, or both, start and end with the empty string, end or both, respectively. Thus, if the string consists of only one instance of separator, the array consists of two empty strings.

If the delimiter is a regular expression containing capturing parentheses, the results of the capturing parentheses (including any undefined results) will be concatenated into the output array each time the delimiter matches. However, not all browsers support this feature.

Remark:  split() returns an array containing an empty string instead of an empty array when the string is empty, or an empty array if both string and delimiter are empty strings.

example

use split()

The following example defines a function: split a string into an array of strings according to the specified delimiter. After delimiting the string, the function outputs the original string information, the delimiter used, the number of returned array elements, and returns all elements in the array in turn.

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: ");

  for (var i=0; i < arrayOfStrings.length; i++)
    console.log(arrayOfStrings[i] + " / ");
}

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);

Copy to ClipboardCopy to Clipboard

The above example outputs the following result:

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 /

Copy to ClipboardCopy to Clipboard

remove spaces from a string

In the following example, split() the method will search for a string of the pattern "0 or more whitespace followed by a semicolon, followed by 0 or more whitespace". When found, the whitespace is removed from the string, and nameList yes  split returns array.

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);

Copy to ClipboardCopy to Clipboard

The above example outputs two lines, the first line outputs the original string, and the second line outputs the result array.

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

Copy to ClipboardCopy to Clipboard

Limit the number of split elements in the returned value

The following example split looks for zero or more spaces in a string and returns the first 3 splits found.

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

console.log(splits);

Copy to ClipboardCopy to Clipboard

The output of the above example:

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

Copy to ClipboardCopy to Clipboard

Segment by regex so that the result contains delimited blocks

If  separator capturing parentheses are included, the matching results will be included in the returned array.

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

console.log(splits);

Copy to ClipboardCopy to Clipboard

The output of the above example:

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

Copy to ClipboardCopy to Clipboard

use an array as separator

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

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

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

const splits = myString.split(['a','b']);
// myString.split(['a','b']) is same as myString.split(String(['a','b']))

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

Copy to ClipboardCopy to Clipboard

Use split() to reverse string order

Warning:  Note that this is not a very robust way to reverse strings:

const str = 'asdfghjkl';
const strReverse = str.split('').reverse().join(''); // 'lkjhgfdsa'
// split() returns an array on which reverse() and join() can be applied

Copy to ClipboardCopy to Clipboard

Unicode-aware splitting (use for example esrever  instead) will not work if the string contains clusters of graphics pixels  .

const str = 'résumé';
const strReverse = str.split(/(?:)/u).reverse().join('');
// => "́emuśer"

Copy to ClipboardCopy to Clipboard

Bonus: use === (en-US) operator to test if the original string was palindrome.

Guess you like

Origin blog.csdn.net/kuang_nu/article/details/129586333