I am trying to replace every word in a string with a certain word.
var str = "hello how are you can you please help me?";
and wish to arrive at the following
answer = "bye bye bye bye bye bye bye bye bye bye";
Currently, I have
var answer = str.replace(/./g, 'bye');
which changes each letter to bye
. How do I change it so that it just targets each word, and not each letter?
You can use this
str.replace(/[^\s]+/g, "bye");
or
str.replace(/\S+/g, "bye");
JS Demo
var str = "hello how are you can you please help me?"; document.writeln("<pre>" + str.replace(/\\S+/g, "bye") + "</br>" + "</pre>");
Small solution ( without regex ):
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"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.