Split Strings withsplit Item above freeCodeCamp

Split Strings withsplit

You can use the split method to split a string into an array by a specified delimiter. You have to pass a parameter to the split method, which will be used as a delimiter.

The following example shows the use of the split method, splitting by the s letter:

var array=string.split(‘s’);

  • Use the split method to split the string string into an array array.

eg: var string = "Split me into an array";

                       var array = [];                      

                      // Only write code below this line                      

                       array= string;                  

correct answer:

var string = "Split me into an array";

var array = [];

var array=string.split(" "); ( separate the string with spaces, I made the spaces larger for easy distinction )

 

Split () details:

The split() method is used to split a string into an array of strings (the split method does not change the original string).

Syntax: stringObject.split(separator,howmany)

Parameter separator: Required. String or regular expression, split stringObject from the place specified by this parameter.

Parameter howmany: optional, set the maximum length of the returned array. If this array 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.

Return value: an array of strings

The array is created by splitting the string stringObject into substrings at the boundaries specified by the parameter separator, and the substrings in the returned array do not include the separator itself.

However, if the separator is a regular expression containing subexpressions, the returned array includes substrings that match those subexpressions (but not text that matches the entire regular expression)

Ps: If an empty string ("") is used as a separator, then each character in the stringObject will be split. Empty strings and whitespace strings are different.

Eg:<script type="text/javascript">

        var str="How are you doing today?”;

document.write(str.split("")); //empty string output H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,? (spaces are also output)

document.write(str.split(" ")); //space string output How,are,you,doing,today?

document.write(str.split(" ",3)); //Control length output How,are,you

There are also some more complex strings:

"2:3:4:5".split(":") //return ["2","3","4","5"]

"|a|b|c".split("|") //return ["","a","b","c"]

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325766247&siteId=291194637