JavaScript RegExp替换 [英] JavaScript RegExp Replace

查看:76
本文介绍了JavaScript RegExp替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定我在哪里做错了。我有一个字符串,如Test(123x),我试图找到(123x)并替换它没有:

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:

这是我的代码

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

我测试了正则表达式模式并且匹配正确,但是,当我登录到控制台时,它是不能用替换(1x)

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

推荐答案

你应尽可能使用 RegExp 文字:

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

您的尝试失败,因为\(\d {1,6 } [x] {1} \)被解释为(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)

除此之外, RegExp 构造函数的第二个参数用于标志( g =全局替换, i =不区分大小写等。)

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

这篇关于JavaScript RegExp替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆