split method

How to split a string into an array of substrings?

JavaScript has many string methods. Today we will explore split() method. As the name suggests it splits a string.

A string is a sequence of characters in a programming language.

Eg: “Abaython”, “JavaScript”.

We can create a string using

  • String literal:

const info = “Hello Abaython!”

  • Using string() constructor:

const info = new String(“Hello Abaython!”);

split() method:

String method used to split a string into an array of substrings using a delimiter. It returns a new array of substrings. It does not change the original string.

Syntax:

               string.split([separator, [,limit]]);

The parameters : separator and limit are optional.

Separator: determines where each split should occur in original string. It can be a string or a regular expression. If you omit this, split() will return the entire string. If (“ “) is used as a separator, the string is split between words.

Limit:

Zero or positive integer to determine the number of substrings. Split() method will stop when number of substrings equals the limit. If limit is zero, returns an empty array. If it is 1, returns an array with the string.

Return value:

               Returns an array of strings, split at each point where separator occurs in given string.

Lets explore some examples:

Without separator:

// without separator

const str = ‘Hello Abaython’;

str.split();

Output:

[‘Hello Abaython’]

How to split a string into individual characters?

We need to use separator here

const str = 'Hello Abaython';

str.split(''); // without space
Output:

 [‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘A’, ‘b’, ‘a’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]

Note that spaces are also considered as characters here.

How to split a string into individual words?

We need to use separator with space.

const str = 'Hello Abaython';
str.split(' '); // with space
Output:

[‘Hello’, ‘Abaython’]

Using limit parameter:

How to return the first word of the given string?

You just need to add the limit as 1 to return first word.

const str = 'Hello Abaython';
str.split(' ',1);
Output:

[‘Hello’]

What will happen if I change the limit to 0?

Lets see,

const str = 'Hello Abaython';
str.split(' ',0);
Output:

[]

It will return an empty array.

How to split the sentences in a paragraph?

let para = 'Hello! JavaScript? Abaython. Abap.';
let sent = para.split(/[!,?,.]/);
console.log(sent);
Output:

[ ‘Hello’, ‘ JavaScript’, ‘ Abaython’, ‘ Abap’, ” ]

As you can see the !,?,. are not included in output. If you want to include them the regular expression should contain parantheses ( ).