Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Replace consecutive spaces with hyphen

Tags:

javascript

Can someone help me with replacing consecutive spaces with a hyphen? For example, I need:

123      321 

to become

123-321

Thanks in advance!

like image 343
Trung Tran Avatar asked May 16 '26 03:05

Trung Tran


2 Answers

var result = "123      321".replace(/ +/g, "-");
console.log(result);

/ +/g = at least 1 space, look globally (in the whole string)

like image 82
Jeremy Thille Avatar answered May 17 '26 16:05

Jeremy Thille


The regular expression \s+ will match any number of consecutive spaces (including tabs and other whitespace characters). Use that as a global pattern for string.replace().

Example from a Javascript console:

> "a     b".replace(/\s+/g, "-")
"a-b"
like image 43
slezica Avatar answered May 17 '26 15:05

slezica