JavaScript: replace last occurrence of text in a string

See my code snippet below:

var list = ['one', 'two', 'three', 'four'];
var str = 'one two, one three, one four, one';
for ( var i = 0; i < list.length; i++)
{
     if (str.endsWith(list[i])
     {
         str = str.replace(list[i], 'finish')
     }
 }

I want to replace the last occurrence of the word one with the word finish in the string, what I have will not work because the replace method will only replace the first occurrence of it. Does anyone know how I can amend that snippet so that it only replaces the last instance of 'one'


Well, if the string really ends with the pattern, you could do this:

str = str.replace(new RegExp(list[i] + '$'), 'finish');

You can use String#lastIndexOf to find the last occurrence of the word, and then String#substring and concatenation to build the replacement string.

n = str.lastIndexOf(list[i]);
if (n >= 0 && n + list[i].length >= str.length) {
    str = str.substring(0, n) + "finish";
}

...or along those lines.