0

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

1
  • 2
    Where do you get the string from? You should fix the problem there. Commented Sep 20, 2011 at 0:42

2 Answers 2

2

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, ", ");
Sign up to request clarification or add additional context in comments.

Comments

0

You can use replace:

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

1 Comment

you need to assign the result of replace() to a new string - it doesn't modify the string you call it on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.