繁体   English   中英

正则表达式替换javascript中匹配的第一次出现

[英]Regex to replace first occurence of match in javascript

我将以下测试用例作为输入:

  1. [This is my test] [This is my test] My name is xyz.

    希望预期输出为:
    [This is my test] My name is xyz.

  2. [This is my test] My name is xyz.
    希望预期输出为:
    My name is xyz.

对于上面的测试用例,我想用空白替换第一次出现的'[This is my test]' 我不想替换第二次匹配。

如何在JavaScript中使用正则表达式解决此问题?

提前致谢。

ETA:

我只想更清楚地说明,我不想在正则表达式中使用硬编码值,我想在正则表达式中使用变量。
假设[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>

如果源字符串不是正则表达式对象而只是字符串,则不需要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 

取代MDN

如果搜索模式位于字符串变量中并且可以包含特殊字符,则必须对其进行转义。 像这样:

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

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, '');

当然。 使用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, ''));

这将做你想要的:

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,"");
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));

这样就可以了:

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, '');
var originalText = '[This is my test] [This is my test] My name is xyz.';
var defaultMsg = "[This is my test] ";

alert( originalText.replace( defaultMsg , '' ) );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM