Join my Laravel for REST API's course on Udemy 👀

JavaScript: Split a string on a character

July 4, 2022  ‐ 1 min read

We use the .split() method of String objects to divide a string up into substrings. Where the substring() method uses an index, we can use split() to separate a string based on a specific character.

In order to split a JavaScript on a dot character we must pass it as the separator string to the split() method.

const IP = '';
const segments = IP.split('.');
//=> (4) ['168', '192', '0', '1']

As you probably noticed the .split() method did split on all the occurrences of the dot character. With a second parameter we can control the amount of elements that are returned to us.

const [subdomain, domain] = ''.split('.', 2);

//=> 'api'

//=> 'example'

As you see the left over substrings are not included in the result array.