Replacing a specific spaces with dashes

50 views Asked by At

Trying to replace specific spaces with dashes and lowercase the string

e.g.

"1.0 Domain - sub & domain"

"1.0-Domain-sub&domain"

Tried

str.replace(/\s+/g, '-').toLowerCase();
-> 1.0-domain---sub-&-domain
1

There are 1 answers

0
The fourth bird On BEST ANSWER

You could capture either - or & between optional whitespace chars and replace that with only the captured char, or else match 1 or more whitespace chars to be replaced with an empty string using the replacer function.

let str = "1.0 Domain - sub & domain";

str = str.replace(/\s*([&-])\s*|\s+/g, (m, g1) => g1 ? g1 : '-').toLowerCase();

console.log(str)