我将以下测试用例作为输入:
[This is my test] [This is my test] My name is xyz.
希望预期输出为:
[This is my test] My name is xyz.
.
[This is my test] My name is xyz.
希望预期输出为:
My name is xyz.
对于上面的测试用例,我想用空白替换第一次出现的'[This is my test]'.我不想替换第二次匹配.
如何在JavaScript中使用正则表达式解决此问题?
提前致谢.
我只想更清楚地说明,我不想在正则表达式中使用硬编码值,我想在正则表达式中使用变量.
假设[This is my test]存储在一个变量中,即var defaultMsg = "[This is my test] ";
有人试过吗?
<script>
var defaultMsg ="[This is my test]"
var str = "[This is my test] [This is my test] My name is xyz.";
str=str.replace(defaultMsg,"");
alert(str);
</script>
Run Code Online (Sandbox Code Playgroud)
如果源字符串不是正则表达式对象而只是字符串,则不需要regexp和replace不关心特殊字符.测试了Mozilla 1.7,FF3.6.6,Safari 5,Opera 10和IE8 windows XP sp3.不确定我理解为什么如果它以最小的麻烦完成工作就被投票.
要替换所有实例,请添加ag(注意:这不是标准的):
str=str.replace(defaultMsg,"","g"); // "gi" for case insensitivity
Run Code Online (Sandbox Code Playgroud)