开发者

How to change comma position in string with javascript

开发者 https://www.devze.com 2023-04-05 20:01 出处:网络
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 be

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

精彩评论

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