我正在尝试用某个词替换字符串中的每个词。
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
。我如何更改它以便它只针对每个单词,而不是每个字母?
最佳答案
你可以用这个
str.replace(/[^\s]+/g, "bye");
或
str.replace(/\S+/g, "bye");
JS 演示
var str = "hello how are you can you please help me?";
document.writeln("<pre>" + str.replace(/\S+/g, "bye") + "</br>" + "</pre>");
关于javascript - 用特定的单词替换每个单词javascript正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37022779/