user6002037
user6002037

Reputation:

replace each word with specific word javascript regex

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

Answers (2)

Ali Mamedov
Ali Mamedov

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

rock321987
rock321987

Reputation: 11042

You can use this

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

or

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>");

Upvotes: 2

Related Questions