Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 600
Brandon Avatar asked May 03 '11 01:05

Brandon


People also ask

How do you replace all occurrences of a regex pattern in a string?

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match.

How do you replace all characters in a string?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.

Can regex replace characters?

RegEx makes replace ing strings in JavaScript more effective, powerful, and fun. You're not only restricted to exact characters but patterns and multiple replacements at once.

How does regex replace work?

The REGEXREPLACE( ) function uses a regular expression to find matching patterns in data, and replaces any matching values with a new string. standardizes spacing in character data by replacing one or more spaces between text characters with a single space.


1 Answers

try

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

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

like image 117
mkoryak Avatar answered Oct 01 '22 13:10

mkoryak