Page 1 of 1

Make regex replace() work on all matches

Posted: 22 Nov 2020, 13:19
by Marius
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?

Make regex replace() work on all matches

Posted: 22 Nov 2020, 14:23
by 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