How to replace last occurrence of characters in a string using javascript
Solution 1:
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')
)
Solution 2:
result = dialog.replace(/,\s(\w+)$/, " and $1");
$1
is referring to the first capturing group (\w+)
of the match.