1

我正在寻找一个 JavaScript 正则表达式,它将在一个句子中查找一个短语,比如“似乎是新的”,如果它找到那个阶段,它会用“似乎”替换整个句子。所以下面的所有句子都将被替换为“似乎”

如何摆脱“您似乎是新人”的消息?
我如何杀死“你似乎是新人”的消息?
如何阻止“您似乎是新来的”消息出现?

4

3 回答 3

1

使用正则表达式的替代方法是使用indexOf

小提琴

var str = 'How do I get rid of the "You seem to be new" message?\n\
How do I get kill the "You seem to be new" message?\n\
How do I stop the "You seem to be new" message from appearing?';

var lines          = str.split('\n')  ,
    search_string  = 'seem to be new' ,
    replace_string = 'seem'           ;

for ( var i=0,n=lines.length; i<n; i++ )
   if ( lines[i].indexOf(search_string) > -1 )
      lines[i] = replace_string ;

alert('original message: \n' + str + '\n\nnew message: \n' + lines.join('\n'));
于 2013-08-24T04:07:53.240 回答
1

您可以String.replace像这样使用该功能:

var newString = (
            'How do I get rid of the "You seem to be new" message?'
          + ' How do I get kill the "You seem to be new" message?'
          + ' How do I stop the "You seem to be new" message from appearing?'
    ).replace(/You seem to be new/g, "seem");

jsFiddle

于 2013-08-24T03:55:16.897 回答
1

这是你想要的?

var str = 'How do I get rid of the "You seem to be new" message? How do I get kill the "You seem to be new" message? How do I stop the "You seem to be new" message from appearing?'
str = str.replace(/[^?!.]*You seem to be new[^?!.]*[?!.]/g,"seem");
console.log(str); // "seemseemseem"

小提琴

此外,如果我输入一个不匹配的字符串,您可以看到会发生什么:

var str = 'How do I get rid of the "You seem to be new" message? How do I get kill the "You seem to be new" message? This sentence doesn\'t seem to contain your phrase. How do I stop the "You seem to be new" message from appearing?'
str = str.replace(/[^?!.]*You seem to be new[^?!.]*[?!.]/g,"seem");
console.log(str); //seemseem This sentence doesn't seem to contain your phrase.seem

小提琴

如果要替换句子但保持相同的标点符号:

var str = 'How do I get rid of the "You seem to be new" message? How do I get kill the "You seem to be new" message? This sentence doesn\'t seem to contain your phrase. How do I stop the "You seem to be new" message from appearing?'
str = str.replace(/[^?!.]*You seem to be new[^?!.]*([?!.])/g," seem$1");
console.log(str); // seem? seem? This sentence doesn't seem to contain your phrase. seem?

小提琴

于 2013-08-24T03:57:10.810 回答