Reputation:
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?
Upvotes: 1
Views: 584
Reputation: 5256
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"
Upvotes: 0
Reputation: 11042
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>");
Upvotes: 2