Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to replace only certain commas

Tags:

javascript

I need a regrex to replace commas are are between two characters that are no spaces.

Text: HOMER, Simpson,JACK, Daniels,NICK, Cage

Desired outcome: HOMER, Simpson - JACK, Daniels - NICK, Cage

This is what I could come up with but it replaces the letters as well as the comma

/[a-zA-z],[a-zA-z]/
like image 322
code511788465541441 Avatar asked Jan 14 '23 13:01

code511788465541441


2 Answers

"HOMER, Simpson,JACK, Daniels,NICK, Cage".replace(/(,(?!\s))/g, ' - ');

http://jsfiddle.net/samliew/sQKNN/

If you need to also check for leading space before a comma,

.replace(/((?!\s),(?!\s))/g, ' - '))
like image 71
Samuel Liew Avatar answered Jan 17 '23 17:01

Samuel Liew


In regex, \S represents all non-space characters.

var input  = "HOMER, Simpson,JACK, Daniels,NICK, Cage";

var output = input.replace(/(\S),(\S)/g, '$1 - $2');
like image 27
Yukulélé Avatar answered Jan 17 '23 17:01

Yukulélé