Home > Mobile >  Replacing a specific spaces with dashes
Replacing a specific spaces with dashes

Time:01-03

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

CodePudding user response:

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)

  • Related