I'm not very familiar with Javascript or Regex but I built a script that is working well with one small flaw in the Regex part. What I want to do is to find commas following alpa-numeric characters (actually almost anything other than a double quote) and then replace the comma with a ~. There are other commas that need to stay as they are so it isn't a simple matter of replacing all commas.

The Regex string that I have at this point is:
/[a-z|0-9]\,/g,"~"

The problem with it is that it replaces the last character in the string as well as the comma. Is there way to change this so it will find the alpha-numeric character followed by the comma but only replace the comma? If not, do I need a loop to find the match and then do a selective replacement (sample code would help if you have some).

Recommended Answers

All 3 Replies

You would need to use backreferences, so you can specify the individual characters, like so:

result = subject.replace(/([a-z|0-9])(,)/ig, "$1~");

$1 points to the char (between the first set of parenthesis), $2 points to the comma.

commented: Good info. Saved me a lot of time trying to search for it. +10

It isn't easy to find good concise info on this topic so I really appreciate your feedback. Your suggested approach worked fine. I learned something useful! Thanks.

I like this site. Next to that he has two nice (paid) tools, RegexBuddy (which I use) and RegexMagic.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.