JavaScript: replace last occurrence of text in a string
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.