1

Why is this code not working as it should?

var temp = "@TEMP (A1)"
var text = "1st Oct @TEMP (A1)"
text = text.replace(new RegExp(temp, "gi"), "");
console.log(text); //I get same text even though I used replace instead of 1st Oct??

Can anybody explain what is going wrong here?

4 Answers 4

6

You need to quote the special characters of temp which is being directly used as your regular expression. The ( and ) characters are grouping characters to the pattern, not actually matching '(' and ')'.

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

Comments

4

Parentheses in regex have special meaning unless escaped:

var temp = "@TEMP \\(A1\\)"

Comments

1

Parenthesis serve a special case in regular expressions. Escape them with a backslash. Also you can use forward-slash notation to create a RegExp object instead.

var loRegExp = /@TEMP \(A1\)/gi;

https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions

Comments

1
var temp = "@TEMP \\(A1\\)";
var text = "1st Oct @TEMP (A1)";
text = text.replace(new RegExp(temp, "gi"), "");
console.log(text);

curly parentheses is a special character in Regexp, you should use backslash to escape it.

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.