Make regex replace() work on all matches

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts: 97

Make regex replace() work on all matches

I’m trying to replace all spaces within a string with hyphens.
I tried this:

Code: Select all

let str ='This is my text';
str = str.replace(/\s/, '-');
console.log(str);  // This-is my text
But it only replaces the first instance of a space and not the ones after it.
What is the regex to make it replace all matches in string?

Admin
Add the global search flag (/g ) to your regex to match all occurrences.

Code: Select all

let str ='This is my text';
str = str.replace(/\s/g, '-');
console.log(str);  // This-is-my-text

Similar Topics