Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String replace with multiple dahses and spaces

Tags:

javascript

I have a number of strings which are formated like this one:

Vincent van Gogh - The Garden of Saint Paul's Hospital (Leaf-Fall) - 12345

And I'm trying to change the string with javascript to this:

Vincent-van-Gogh-The-Garden-of-Saint-Pauls-Hospital-Leaf-Fall-12345

I'm essentialy wanting to strip out ,'() from the titles, change the " - " and blank spaces to "-".

I can strip the punctuation like this:

str.replace(/[,'()]/g,"");

So I tried this to try and get rid of that space dash space:

replace(/[ - ]/g,"");

But then I end up with this:

VincentvanGogh-TheGardenofSaintPaul'sHospital(Leaf-Fall)-12345

like image 213
Siwap Avatar asked Jan 03 '23 00:01

Siwap


1 Answers

Your are using a character class [ - ] to a range from a whitespace to a whitespace. You could remove one of the whitespaces and repeat that one or more times [ -]+ and replace that with a dash:

let str = "Vincent van Gogh - The Garden of Saint Paul's Hospital (Leaf-Fall) - 12345";
console.log(str.replace(/[,'()]/g,"").replace(/[ -]+/g, '-'));
like image 122
The fourth bird Avatar answered Jan 05 '23 17:01

The fourth bird