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 = '168.192.0.1';
const segments = IP.split('.');
console.log(segments);
//=> (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] = 'api.example.com'.split('.', 2);
console.log(subdomain);
//=> 'api'
console.log(domain);
//=> 'example'
As you see the left over substrings are not included in the result array.