The reason for the error is that you have to escape characters that have special meaning in regular expressions, like )
and $
.
But just fixing that won't get you to the output you're looking for, where you want to split on the special tags, remove the ()
in the tags, and keep them. I don't think there's a single regex solution for this with JavaScript's regexes (perhaps someone smarter than I knows a way, but with the transforming $(tag1)
to $tag1
I'm not getting there). But we can get there with a couple of replaces and a split:
var input = "$(tag1)sample$(tag2)";
var splitStrings = input.replace(/\$\(([^)]+)\)/g, "\t$$$1\t")
.replace(/(?:^\t+)|(?:\t+$)/g, '')
.split(/\t+/);
console.log(splitStrings);
The first replace transforms $(tag1)
to \t$tag1\t
(e.g., puts tabs around it and removes the ()
). The second replace gets rid of any leading and trailing tabs. Then the split splits on any sequence of tabs.
Of course, if tabs may occur in the string and you want to keep them, just replace them with anything else that suits.