我将以下测试用例作为输入:
[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] ";
答案 0 :(得分:6)
有人试过吗?
<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>
如果源字符串不是正则表达式对象而只是字符串,则不需要regexp和replace不关心特殊字符。 测试了Mozilla 1.7,FF3.6.6,Safari 5,Opera 10和IE8 windows XP sp3。不确定我理解为什么如果它以最小的麻烦完成工作就会被拒绝。
要替换所有匹配项,请添加g(注意:这不是标准的):
str=str.replace(defaultMsg,"","g"); // "gi" for case insensitivity
答案 1 :(得分:3)
如果搜索模式位于字符串变量中并且可以包含特殊字符,则必须对其进行转义。像这样:
var defaultMsg = "[This is my test] ";
//-- Must escape special characters to use in a RegEx.
defaultMsg = defaultMsg.replace (/([\!\$\(\)\*\+\.\/\:\=\?\[\\\]\^\{\|\}])/g, "\\$1")
var zRegEx = new RegExp (defaultMsg, '');
var Str = '[This is my test] [This is my test] My name is xyz.';
Str = Str.replace(zRegEx, "");
console.log (Str); //-- Or use alert()
答案 2 :(得分:0)
JavaScript replace
函数默认为非全局,因此它只替换第一个匹配项:
var foo = '[This is my test] [This is my test] My name is xyz.';
var bar = foo.replace(/\[This is my test\]\s/, '');
如果您想要替换字符串的所有次出现,请通过附加g
来使全局正则表达式全局:
var bar = foo.replace(/\[This is my test\]\s/g, '');
答案 3 :(得分:0)
不确定。使用replace()
:
var s = "[This is my test] [This is my test] My name is xyz.";
alert(s.replace(/\[This is my test\] /, ''));
如果您要替换所有次出现:
alert(s.replace(/\[This is my test\] /g, ''));
答案 4 :(得分:0)
这将做你想要的:
str= '[This is my test] [This is my test] My name is xyz.';
str = str.replace(/\[This is my test\]/,"");
要替换所有出现的' [这是我的测试] ,您需要致电:
str = str.replace(/\[This is my test\]/g,"");
答案 5 :(得分:0)
var str="[This is my test] [This is my test] My name is xyz.?";
var patt1=(/[[This is my test]].*My name is xyz/i);
document.write(str.match(patt1));
答案 6 :(得分:0)
这样可以解决问题:
var foo = '[This is my test] ';// or whatever you want
foo = foo.replace(/([\[\]])/, '\\$1', 'g'); // add all special chars you want
var patern = new RegExp(foo);
var myString = '[This is my test] [This is my test] My name is xyz.';
var result = myString.replace(patern, '');
答案 7 :(得分:0)
var originalText = '[This is my test] [This is my test] My name is xyz.';
var defaultMsg = "[This is my test] ";
alert( originalText.replace( defaultMsg , '' ) );