jfutch
jfutch

Reputation: 385

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",")",")"]

Upvotes: 0

Views: 236

Answers (1)

falsetru
falsetru

Reputation: 369424

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", ")", ")"]

Upvotes: 1

Related Questions