Alex Rivera | Logout

How to replace last occurrence of characters in a string using javascript

Asked 2010-09-30T09:50:31.220
48

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

Edit
Report

1 Answer

78
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.

console.log( 
   'test1, test2, test3'.replace(/,\s([^,]+)$/, ' and $1') 
)

answered 2010-09-30T09:59:05.050

Your Answer