The default behavior of the split() method is that when you split a string using the split()
method, it removes the separator from the array of substrings.
let str = "a-b-c-d-e"; console.log(str.split("-")); //["a", "b", "c", "d", "e"] console.log(str.split(/-/)); //["a", "b", "c", "d", "e"]
You can see that the separator is removed from the array returned by the split() method.
So, if you want to keep the delimiter, then use the capturing group. In a regular expression, parenthesis ()
is called capturing group.
Using the capturing group, you can keep the delimiter in the array of substrings returned by the split() method.
let str = "a-b-c-d-e"; console.log(str.split(/(-)/)); //["a", "-", "b", "-", "c", "-", "d", "-", "e"]
Similarly, with the help of parenthesis, you can split a string and keep whitespace.
let str = "Pizza Burger Sandwich"; console.log(str.split(/(\s)/)); //["Pizza", " ", "Burger", " ", "Sandwich"]
\s
represents a whitespace character. Whitespace character can be space, tab and new line.