views:

89

answers:

3

Hi

I'm having a problem finding out how to replace the last ', ' in a string with ' and ':

Having this string: test1, test2, test3

and I want to end out with: test1, test2 and test3

I'm trying something like this:

var dialog = 'test1, test2, test3';    
dialog = dialog.replace(new RegExp(', /g').lastIndex, ' and ');

but it's not working

A: 

Try replacing new RegExp(', /g') with /, /g

Philippe Leybaert
Yielding `dialog = dialog.replace(/, /g.lastIndex, ' and ');`, which still doesn't make much sense (attempts to replace "0" with " and ").
T.J. Crowder
That's why I said "try" :-) The syntax of the regex was incorrect, which was the first thing I noticed in the code snippet.
Philippe Leybaert
+1  A: 
result = dialog.replace(/,\s(\w+)$/, " and $1");

$1 is referring to the first capturing group (\w+) of the match.

splash
Example: http://jsbin.com/utedu
T.J. Crowder
`g` modifier isn't needed.
M42
@M42, thanks for the hint. I removed it.
splash
This will fail for strings like 'test-1, test-2, test-3', but again I'm confident the OP can make such adaptations themself.
annakata
That's right @annakata.
splash
+3  A: 
foo.replace(/,([^,]*)$/, ' and $1')

use the $ (end of line) anchor to give you your position, and look for a pattern to the right of the comma index which does not include any further commas.

Edit:

The above works exactly for the requirements defined (though the replacement string is arbitrarily loose) but based on criticism from comments the below better reflects the spirit of the original requirement.

foo.replace(/,\s([^,]+)$/, ' and $1')
annakata
+1, probably better than using `\w` as splash did as it's more inclusive, example: http://jsbin.com/utedu/2
T.J. Crowder
This also matches `test1, test2,` and produces `test1, test2 and ` for it. Also it inserts a redundant space character for the original input string, because it forgets to match the space character after the `,`.
splash
@splash - see edit. I'm pretty confident the OP could have made that modification himself if the requirement is more detailed than expressed, I don't want to make presumptions about what people really meant to say.
annakata
@annakata - me neither! ;-)
splash