I'm trying to modify a string using javascript. I should replace all of whitespace to -, except the space is before or after a dash.
For example:
const url= 'This is an - url';
let newUrl = url.replace(/\s+/g,'-');
let newUrlLowerCase = newUrl.toLowerCase();
it's give me result this-is-an---url, what I need is this-is-an-url
How do I can do that with javascript?
You can match a space or a dash, in a character set, and repeat it, replacing with a single dash:
const url = 'This is an - url';
let newUrl = url.replace(/[\s-]+/g, '-').toLowerCase();
console.log(newUrl);
You could replace the - with ' ' before space replace
const url= 'This is an - url';
let newUrl = url.replace('-',' ').replace(/\s+/g,'-')
let newUrlLowerCase = newUrl.toLowerCase();
console.log(newUrlLowerCase)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With