简体   繁体   中英

Javascript Regexp split by multiple characters and keeping separator

I'm trying to split by the following by multiple characters and keep them in the array.

split by: &&, ||, (, )

"arg&&(arg||(!arg&&arg))".split(/([)||&&(])/);

My return is suppose to look like this:

["arg","&&","(","arg","||","(","!arg","&&","arg",")",")"]

Capturing groups are kept in resulting array.

| should be escaped, because it have special meaning in regular expression. ( and ) also have special meaning, but inside [] , they match literally.

> "arg&&(arg||(!arg&&arg))".split(/([()]|&&|\|\|)/)
["arg", "&&", "", "(", "arg", "||", "", "(", "!arg", "&&", "arg", ")", "", ")", ""]

To remove empty string, use Array filter method :

> "arg&&(arg||(!arg&&arg))".split(/([()]|&&|\|\|)/).filter(function(x) { return x; })
["arg", "&&", "(", "arg", "||", "(", "!arg", "&&", "arg", ")", ")"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM