3

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

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.