Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript replace space to dash except space before and after a dash

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?

like image 736
Blackjack Avatar asked Jun 08 '26 03:06

Blackjack


2 Answers

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);
like image 75
CertainPerformance Avatar answered Jun 10 '26 04:06

CertainPerformance


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)
like image 33
prasanth Avatar answered Jun 10 '26 03:06

prasanth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!