Sometimes, we want to split string and keep the separator with JavaScript and regex.
In this article, we’ll look at how to split string and keep the separator with JavaScript and regex.
How to split string and keep the separator with JavaScript and regex?
To split string and keep the separator with JavaScript and regex, we can call string’s split
method with a regex.
For instance, we write
const a = "1、2、3".split(/(、)/g)
to call split
with /(、)/g
to return an iterable object with all the values around the delimier 、
in addition to the delimiters themselves.
Therefore, we get returned.
["1", "、", "2", "、", "3"]
Conclusion
To split string and keep the separator with JavaScript and regex, we can call string’s split
method with a regex.