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.
const IP = '184.108.40.206'; 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.