2

Not sure where I am doing wrong. I have a string such as Test (123x) and I am trying to find the (123x) and replace it with nothing:

Here is my code

<script type="text/javascript">
    var original = "Test (1x)";
    var newString = original.replace(new RegExp("\(\d{1,6}[x]{1}\)",original),"");
    console.log(newString);
</script>

I have tested the regex pattern and it matches correctly, however, when I log to the console, it's not replacing (1x) with ""

1
  • You might want to use the regular expression syntax to make your code a bit shorter: original.replace(/\(\d{1,6}[x]{1}\)/, "") Commented Jun 3, 2011 at 16:40

2 Answers 2

9

You should use the RegExp literals when possible:

var original = "Test (1x)";
var newString = original.replace(/\(\d{1,6}[x]{1}\)/,"");

Your attempt fails as "\(\d{1,6}[x]{1}\)" is interpreted as "(d{1,6}[x]{1})" (\‍ are simply stripped for unknown escape sequences). You would need to escape the \ as well:

new RegExp("\\(\\d{1,6}[x]{1}\\)",original)

Besides that, the second parameter for the RegExp constructor is for the flags (g=global replace, i=case insensitive, etc.).

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

Comments

3

Passing original to the RegExp is wrong. You also have to escape every slash in the string (so that it produces a slash for the regex) as \ is the escape character in JS strings:

original.replace(new RegExp("\\(\\d{1,6}[x]{1}\\)"),"");

Note that [x]{1} is the same as writing x directly.

You could also use a regex literal:

/\(\d{1,6}x\)/

1 Comment

Makes sense, since replace is called on original, but this still logs Test (1x)

Your Answer

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