Javascript and regex: keeping the separator when splitting a string
The objective is to split a string with a specific delimiter, but also retain the delimiter. An example string is "aaaaaa
† bbbb
‡ cccc", which needs to be split using "
&" followed by a special character.
The initial approach, string.split(/
[a-zA-Z0-9] ;/g), eliminates the delimiter. To preserve it, consider the following options:
"1、2、3".split(/(、)/g) == ["1", "、", "2", "、", "3"]
Note that this method can be used to split characters or sequences of characters.
"1、2、3".split(/(?!、)/g) == ["1、", "2、", "3"]
This approach will prevent splitting at a particular delimiter.
"1、2、3".split(/(.*?、)/g) == ["", "1、", "", "2、", "3"]
This method allows for capturing the delimiter in a separate group, providing more flexibility.
// Split a path, but keep the slashes that follow directories var str = 'Animation/rawr/javascript.js'; var tokens = str.match(/[^\/]+\/?|\//g);
This approach can be used for complex splitting scenarios, such as preserving slashes in a file path.
The above is the detailed content of How Can I Split a String in Javascript While Retaining the Delimiter?. For more information, please follow other related articles on the PHP Chinese website!