Categories
JavaScript Answers

How to split string into array without deleting delimiter with JavaScript?

Spread the love

Sometimes, we want to split string into array without deleting delimiter with JavaScript.

In this article, we’ll look at how to split string into array without deleting delimiter with JavaScript.

How to split string into array without deleting delimiter with JavaScript?

To split string into array without deleting delimiter with JavaScript, we can put our regex pattern in a capturing group and use the string’s split method to split the string.

For instance, we write:

const arr = "asdf a  b c2 ".split(/( )/).filter(String)
console.log(arr)

To split the "asdf a b c2 " string with split with a space as the separator and keep all the separators in the returned array.

Then we call filter to return all the parts that aren’t falsy when we use String to convert them to strings with filter.

Therefore, arr is ['asdf', ' ', 'a', ' ', ' ', 'b', ' ', 'c2', ' '].

Conclusion

To split string into array without deleting delimiter with JavaScript, we can put our regex pattern in a capturing group and use the string’s split method to split the string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *