我的字符串是“增加住房成本,创造经济安全感,减少旅行,家庭幸福,金融安全”。我想使用JavaScript删除字符串中的空格和额外逗号。因此,最后一个字符串应该是,“增加住房成本,创造金融安全感,减少旅行,家庭幸福,金融安全”,来自一个变量"myString“,我尝试使用myString = myString.replace(", ,",",");,但它不起作用。
发布于 2022-09-26 18:41:56
将,和,与它们之间的空白(或无)匹配。这被称为正则表达式或regexp,它是一种描述可以在文本上执行的操作的语言(这是我的免费解释)。
在这个特定的实例中,这匹配逗号,后面是\s (空格)0或更多次*,然后是逗号。结尾的g意味着匹配的不仅仅是第一个。
var reg = /,\s*,/g
console.log("Increase in housing cost, Create sense of Financial security, Reduced Travel, ,Happiness for Family, Financial Security".replace(reg, ', '))
发布于 2022-09-26 18:43:04
let myString = "Increase in housing cost, Create sense of Financial security, Reduced Travel, ,Happiness for Family, Financial Security";
myString = myString.replaceAll(", ,",",")https://stackoverflow.com/questions/73858542
复制相似问题