techStackGuru

JavaScript String Split method


A string can be divided into an array of substrings using JavaScripts split function by specifying a delimiter.

Syntax

string.split(separator)
string.split(separator, limit)

Separator : When splitting a string, it is used to identify the character or regular expression to be executed.

Limit : Specifies the maximum number to be executed.

Example

let str = "a b c";
const arr = str.split(" ");

console.log(arr); // [ 'a', 'b', 'c' ] 

Letter separator

let str = "Go for it";
const arr = str.split('i');

console.log(arr); // [ 'Go for ', 't' ]

Example

let str = "justdoit";
const arr = str.split('do');

console.log(arr); // [ 'just', 'it' ]

Limit the parameter

let str = "a b c d e f";
const arr = str.split(" ", 3);

console.log(arr); // [ 'a', 'b', 'c' ]