JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to split a string without removing delimiter in JavaScript?

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.

Recommended Posts