javascript - How to prevent this regex that replaces hyphens with spaces from also replacing hyphens with additional hyphens? -


this regex:

str.replace(/ +/g, '-').tolowercase(); 

will convert this:

the dog jumped on lazy - chair 

into this:

the-dog-jumped-over-the-lazy---chair 

how modify produces instead (only single hyphen):

the-dog-jumped-over-the-lazy-chair 

i assume actual input "the dog jumped on lazy - chair", spaces around hyphen getting converted, since there's no other reason pattern should match there.

try this:

str.replace(/( +- *)|(- +)|( +)/g, '-').tolowercase(); 

that explicitly checks strings of spaces on either side of hyphens (the first pattern designed consume trailing space), consuming 1 hyphen in process. if hyphen exists surrounded spaces, hyphen included in match, when hyphen written, "replacement"; in case, spaces removed, , hyphen re-created replace operation because captured part of expression.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -