我试图用某个单词替换字符串中的每个单词。
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
。如何更改它以便它只针对每个单词,而不是每个字母?
答案 0 :(得分:2)
您可以使用此
str.replace(/[^\s]+/g, "bye");
或
str.replace(/\S+/g, "bye");
<强> Regex Demo 强>
JS Demo
var str = "hello how are you can you please help me?";
document.writeln("<pre>" + str.replace(/\S+/g, "bye") + "</br>" + "</pre>");
&#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"