用特定单词javascript regex替换每个单词

时间:2016-05-04 08:50:25

标签: javascript regex

我试图用某个单词替换字符串中的每个单词。

var str = "hello how are you can you please help me?";

并希望到达以下

answer = "bye bye bye bye bye bye bye bye bye bye";

目前,我有

var answer = str.replace(/./g, 'bye');

将每个字母更改为bye。如何更改它以便它只针对每个单词,而不是每个字母?

2 个答案:

答案 0 :(得分:2)

您可以使用此

str.replace(/[^\s]+/g, "bye");

str.replace(/\S+/g, "bye");

<强> Regex Demo

JS Demo

&#13;
&#13;
var str = "hello how are you can you please help me?";
document.writeln("<pre>" + str.replace(/\S+/g, "bye") + "</br>" + "</pre>");
&#13;
&#13;
&#13;

答案 1 :(得分:0)

小解决方案(没有正则表达式):

var 
  str = "hello how are you can you please help me?";

str.split(' ').map(function(a) {

  if (a === '') return;

  return 'bye';

}).join(' '); // "bye bye bye bye bye bye bye bye bye"