我有一些字符串,格式如下:
Vincent van Gogh - The Garden of Saint Paul's Hospital (Leaf-Fall) - 12345
我正在尝试使用 javascript 将字符串更改为:
Vincent-van-Gogh-The-Garden-of-Saint-Pauls-Hospital-Leaf-Fall-12345
我本质上想从标题中删除 ,'()
,将“-”和空格更改为“-”。
我可以像这样去除标点符号:
str.replace(/[,'()]/g,"");
所以我尝试这样做来尝试摆脱那个空格破折号空间:
replace(/[ - ]/g,"");
但后来我得到了这个:
VincentvanGogh-TheGardenofSaintPaul'sHospital(Leaf-Fall)-12345
最佳答案
您正在使用字符类 [ - ]
来处理从一个空格到一个空格的范围。您可以删除其中一个空格并重复一次或多次 [ -]+
并将其替换为破折号:
let str = "Vincent van Gogh - The Garden of Saint Paul's Hospital (Leaf-Fall) - 12345";
console.log(str.replace(/[,'()]/g,"").replace(/[ -]+/g, '-'));
关于javascript - 字符串替换为多个破折号和空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51790976/