开发者

JavaScript RegExp Replace

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 rege开发者_StackOverflow中文版x pattern and it matches correctly, however, when I log to the console, it's not replacing (1x) with ""


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜