Regex only replace some commas

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

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

Desired result: 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]/ 
+4
source share
4 answers
 "HOMER, Simpson,JACK, Daniels,NICK, Cage".replace(/(,(?!\s))/g, ' - '); 

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

If you need to also check the starting space before the decimal point,

 .replace(/((?!\s),(?!\s))/g, ' - ')) 
+3
source

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

 var input = "HOMER, Simpson,JACK, Daniels,NICK, Cage"; var output = input.replace(/(\S),(\S)/g, '$1 - $2'); 
+3
source

This is not so difficult to achieve.

  • the \S character class represents all characters without spaces.
  • You can use parentheses () to capture a group. In the replacement line, you can refer to each captured group using $0 (which represents the entire match), $1 (which represents the first group), $2 , $3 , etc., which represent the subsequent groups.

The following code does what you want:

 var input = "HOMER, Simpson,JACK, Daniels,NICK, Cage" , output = input.replace(/(\S),(\S)/g, '$1 - $2'); 

Note that since \S is the equivalent of [ \t\r\n] (that is, any of the following characters: space, tab, CR [carriage return], LF [line]], and \S is the inverse of \S , \S also will not match the tab or newline character.

+2
source

Try

 'HOMER, Simpson,JACK, Daniels,NICK, Cage'.replace(/([^\s]),([^\s])/gi, '$1 - $2'); 
+1
source

All Articles