How to split the string based on delimiter in Javascript?

Split Method in Javascript

The Split method is used to split a string into an array of strings and breaking at a specified delimiter string or regular expression. Basically it is breaking the string before and after that matching delimiter/separator.If the delimiter is not specified in the argument, it returns the complete string in a single array element.

Syntax for Split method in Js:

delimiter: The delimiter is treated as a string or regular expression. It specify the point where the split needs to takes place.If the separator is an empty string(“”), each character of the string will be separated.

limit: Its is an optional integer argument. It specifies the maximum length of the returned array. The split method() splits the string at each occurrence of the specified separator but stops when limit entries have been placed into the array.If the limit is not specified, the divided strings are placed into the array regardless of its length.

Returns: The split() method returns an array of as many as limit sub strings of the specified string.

Example 1:Split the string using the delimiter as space

Since we have specified the delimiter as space(” “), the split() method is divided the given string “Revisit Class” into two sub string as “Revisit” and “Class” that is returned in the array as below.

Output

[Revisit,Class]

Example 2:Split the string using the delimiter as exclamation symbol(!)

Here the delimiter string is exclamation mark(!) in the split method. Since the given string “Great!Well done!Good job” contains the exclamation mark, the split method break the string into number of sub strings such as Great,Well done,Good job.

Output

[Great,Well done,Good job]

Example 3: Split each character in the string including white space

Here the delimiter specified as empty string(“”) in the split method. so it returns the each character from the given string in a array.

Output

[ N,i,c,e, ,t,o, ,m,e,e,t, ,y,o,u]

Example 4 : Split the string with the limit parameter

Since we have given the limit as 4 in the split method, it returns only the 4 elements in a array as below.

Output

[N,i,c,e]