找到短语时替换整个句子

时间:2013-08-24 03:50:21

标签: javascript regex

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

  

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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"

Fiddle

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

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

Fiddle

如果您想替换句子但保留相同的标点符号:

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?

Fiddle

答案 2 :(得分:1)

使用正则表达式的另一种方法是使用indexOf

Fiddle

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