开发者

How to change comma position in string with javascript

I have an 开发者_高级运维issue where my commas are misplaced in the string. Anyone know a replace or a similar function that could move my commas to the correct grammatical position? Example posted below:

Cabernet Sauvignon ,Marsanne ,Red Blend ,Syrah ,Zinfandel

I need it to look like this:

Cabernet Sauvignon, Marsanne, Red Blend, Syrah, Zinfandel


The simple version is like this:

var str = "Cabernet Sauvignon ,Marsanne ,Red Blend ,Syrah ,Zinfandel";
var newStr = str.replace(/ ,/g, ", ");

If you wanted to get fancier and require non-space characters to be on the boundaries of what you were changing or collapse extra spaces, that could also be added to the regular expression, but you'd have to describe what you want.

For example, this will collapse multiple spaces or tabs on either side of the comma to have just one space after the comma:

var newStr = str.replace(/\s*,\s*/g, ", ");


You can use replace:

var str = "Cabernet Sauvignon ,Marsanne ,Red Blend ,Syrah ,Zinfandel";
str.replace(/ ,/g,", ");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜