Javascript - Replace sequential spaces with hyphen

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

123      321 

      

to become

123-321

      

Thanks in advance!

+3


source to share


2 answers


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

Run code




/ +/g

= at least 1 space, look globally (in the whole line)

+7


source


The regex \s+

will match any number of consecutive spaces (including tabs and other whitespace characters). Use this as a global template for string.replace()

.

Example from Javascript Console:



> "a     b".replace(/\s+/g, "-")
"a-b"

      

+1


source







All Articles