[英]JavaScript - how to remove certain whitespaces in string
For Example, I have a string like this: 例如,我有一个像这样的字符串:
"1 - A1, 2 - A2, 3 - A3";
I want to remove the white spaces ONLY after the commas, NOT the white space in between the hypens "-" so end result looks like this: 我只想在逗号后删除空格,而不要在连字符“-”之间删除空格,因此最终结果如下所示:
"1 - A1,2 - A2,3 - A3";
currently I'm doing: 目前我正在做:
myString.replace(/\s/g, '');
but this removes all whitespace, including whitespace on both sides of the hyphens. 但这会删除所有空格,包括连字符两侧的空格。 I just want to remove the whitespace after the commas.
我只想在逗号后删除空格。
Is this doable? 这可行吗?
Thanks 谢谢
You can use: 您可以使用:
var str = "1 - A1, 2 - A2, 3 - A3";
var r = str.replace(/,\s+/g, ',');
//=> "1 - A1,2 - A2,3 - A3"
,\\s+
will all commas with at least one whitespace afterwards. ,\\s+
所有逗号都将至少带有一个空格。
如果在这些逗号后始终始终只有一个空格字符,则为简单的解决方案:
"1 - A1, 2 - A2, 3 - A3".split(", ").join(",");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.