1

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?

10
  • Each "word" or a chunk of non-whitespace characters? Commented May 4, 2016 at 8:51
  • I am looking to replace each word Commented May 4, 2016 at 8:52
  • 1
    Then, no need using regex, see Ali's solution. Commented May 4, 2016 at 8:54
  • 1
    Choose what is easier for you. I do not insist on anything. Commented May 4, 2016 at 8:57
  • 1
    if there is anything that can be done without regex(and is not complicated), you should avoid regex Commented May 4, 2016 at 9:01

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

@WiktorStribiżew thanks..i always forget small things
0

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.