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.
source share