JavaScript RegExp Replace

2019-06-02 09:43发布

问题:

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 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.).



回答2:

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\)/