Skip to content
Advertisement

How to make this regex replace work on all characters, not just the first?

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

h3Text.replace(/s/, '-');

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 empty spaces?

Advertisement

Answer

try

h3Text.replace(/s/g, '-');

the g flag is key here. it means global replace, ie replace all

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement