Reputation: 549
I am using this tool to build a regex http://www.gethifi.com/tools/regex
I found that the one below works for me if, for example, I am looking to match $aazz[AB]
:
var regex = /[\+\=\-\*\^\\]\$aazz\[AB\]/g;
I have read the other posts on the RegEx constructor in Javascript but cannot manage to make the following work:
var preToken = "[\+\=\-\*\^\\]";
var toFind = "\$aazz\[AB\]";
var stringToReplace = "/" + preToken + toFind + "/";
var regex = new RegExp(stringToReplace, "g");
Here is the jsbin http://jsbin.com/ifeday/3/edit
Thanks
Upvotes: 3
Views: 343
Reputation: 16020
When creating regular expressions from strings, you need to escape your backslashes twice.
\ becomes \\
\\ becomes \\\\
So, you can try (in a character class not everything needs escaping):
var preToken = "[+=\\-*^\\\\]";
var toFind = "azz\\[A\\]";
Also, the string source for your regular expression does not need to be bound by /
s, but I see in your jsBin that you've already corrected that.
Update your jsBin with these variable declarations, it should work now.
Upvotes: 4