JavaScript string object a primer instance of the split method (for splitting strings into arrays)

  • 2020-03-30 04:06:26
  • OfStack

The JavaScript split method

The split method is used to split a string into an array of strings and return that array. The syntax is as follows:


str_object.split(separator, limit)

Parameter description:

parameter instructions
str_object String (object) to manipulate
separator A necessity. A delimiter, string, or regular expression, separated from where the parameter is specified str_object
limit Optional. Specifies the maximum length of the returned array. If this parameter is set, no more substrings are returned than the array specified by this parameter. If the parameter is omitted, all conforming rules are split

Tip: if the empty string ("") is used as separator, each character in str_object is separated, as in the following example.

Split method instance


<script language="JavaScript"> var str = "www.jb51.net";
document.write( str.split(".") + "<br />" );
document.write( str.split("") + "<br />" );
document.write(str.split(".", 2)); </script>

Run the example and output:


www,jb51,net
w,w,w,.,j,b,5,1,.,n,e,t
www,jb51

Tip: if the empty string ("") is used as separator, as shown in the example above, each character in str_object is split.

The split method USES regular expressions


<script language="JavaScript"> document.write( "1a2b3c".split(/d/) + "<br />");
document.write( ":a:b:c".split(":") ); </script>

Run the example and output:


a,b,c
,a,b,c

Look carefully at the differences in the output of the two examples.


Related articles: