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

str = str.replace(new RegExp(list[i] + '$'), 'finish');
Answer from Pointy on Stack Overflow
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › string › replace last occurrence
Replace the last occurrence of a pattern in a JavaScript string - 30 seconds of code
February 8, 2024 - const replaceLast = (str, pattern, replacement) => { const match = typeof pattern === 'string' ? pattern : (str.match(new RegExp(pattern.source, 'g')) || []).slice(-1)[0]; if (!match) return str; const last = str.lastIndexOf(match); return last !== -1 ? `${str.slice(0, last)}${replacement}${str.slice(last + match.length)}` : str; }; replaceLast('abcabdef', 'ab', 'gg'); // 'abcggdef' replaceLast('abcabdef', /ab/, 'gg'); // 'abcggdef' replaceLast('abcabdef', 'ad', 'gg'); // 'abcabdef' replaceLast('abcabdef', /ad/, 'gg'); // 'abcabdef' ... If you need to replace all occurrences of a string in JavaScript, you have a couple of options.
Discussions

regex - Replace last occurrence word in javascript - Stack Overflow
I have a problem with replacing last word in JS, I am still searching solution but i cannot get it. I have this code: var string = $(element).html(); // "abc def abc xyz" var word = "abc"; var More on stackoverflow.com
🌐 stackoverflow.com
regex - javascript replace last occurrence of string - Stack Overflow
I've read many Q&As in StackOverflow and I'm still having a hard time getting RegEX. I have string 12_13_12. How can I replace last occurrence of 12 with, aa. Final result should be 12_13_aa.... More on stackoverflow.com
🌐 stackoverflow.com
regex - How to replace last occurrence of characters in a string using javascript - Stack Overflow
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 some... More on stackoverflow.com
🌐 stackoverflow.com
Javascript string replace last ocurrence - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
🌐 stackoverflow.com
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-replace-last-occurrence-of-character-in-string
Replace Last Occurrence of Character in String in JavaScript | bobbyhadz
If you need to replace the last occurrence of a substring, use the replacement string's length to determine the start index in the second call to the slice() method.
🌐
DaniWeb
daniweb.com › programming › web-development › threads › 345778 › replace-last-occurence-of-a-substring-from-a-string
javascript - Replace last occurence of a substring from ... | DaniWeb
Case for any more than 1 -> xxx, yyy, str = str.replace(/,\s*$/, "") // Done! Case for only 1 appear -> xxx, (won't interfere with the case 1) ... Your function is correct, but there are a lot going on. :) And there's a reason for that. From the context of the OP's post, they clearly aren't familiar with JavaScript or perhaps programming methodologies (probably both).
🌐
LabEx
labex.io › tutorials › replace-last-occurrence-in-string-28594
Replace the Last Occurrence in a String | LabEx
In this lab, we will explore string manipulation in JavaScript by implementing a replaceLast function. Unlike the built-in replace method which replaces the first occurrence of a pattern, our function will specifically target the last occurrence.
Top answer
1 of 7
26

Here is an idea ....

This is a case-sensitive string search version

var str = 'abc def abc xyz';
var word = 'abc';
var newWord = 'test';

// find the index of last time word was used
// please note lastIndexOf() is case sensitive
var n = str.lastIndexOf(word);

// slice the string in 2, one from the start to the lastIndexOf
// and then replace the word in the rest
str = str.slice(0, n) + str.slice(n).replace(word, newWord);
// result abc def test xyz

If you want a case-insensitive version, then the code has to be altered. Let me know and I can alter it for you. (PS. I am doing it so I will post it shortly)

Update: Here is a case-insensitive string search version

var str = 'abc def AbC xyz';
var word = 'abc';
var newWord = 'test';

// find the index of last time word was used
var n = str.toLowerCase().lastIndexOf(word.toLowerCase());

// slice the string in 2, one from the start to the lastIndexOf
// and then replace the word in the rest
var pat = new RegExp(word, 'i')
str = str.slice(0, n) + str.slice(n).replace(pat, newWord);
// result abc def test xyz

N.B. Above codes looks for a string. not whole word (ie with word boundaries in RegEx). If the string has to be a whole word, then it has to be reworked.

Update 2: Here is a case-insensitive whole word match version with RegEx

var str = 'abc def AbC abcde xyz';
var word = 'abc';
var newWord = 'test';

var pat = new RegExp('(\\b' + word + '\\b)(?!.*\\b\\1\\b)', 'i');
str = str.replace(pat, newWord);
// result abc def test abcde xyz

Good luck :)

2 of 7
8
// create array
var words = $(element).html().split(" ");

// find last word and replace it
words[words.lastIndexOf("abc")] = newWord 

// put it back together
words = words.join(" ");
🌐
Know Program
knowprogram.com › home › javascript replace last occurrence
JavaScript Replace Last Occurrence - Know Program
November 9, 2022 - Pattern:- a string or an object containing a symbol might both be used. The replace approach is a regular expression and a common illustration. Any value without the Symbol.replace() method will have its value forced to be a string.
Find elsewhere
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-replace-last-character-in-string
Replace the Last Character in a String in JavaScript | bobbyhadz
March 1, 2024 - Use the String.substring() method to get a portion of the string up to the last character. Use the addition (+) operator to add the replacement.
Author: bobbyhadz
🌐
YouTube
youtube.com › hey delphi
JavaScript : Replace last occurrence of character in string - YouTube
JavaScript : Replace last occurrence of character in stringTo Access My Live Chat Page, On Google, Search for "hows tech developer connect"As I promised, I h...
Published: May 1, 2023
Views: 16
🌐
GitHub
github.com › Chalarangelo › 30-seconds-of-code › blob › master › content › snippets › js › s › replace-last-occurrence.md
30-seconds-of-code/content/snippets/js/s/replace-last-occurrence.md at master · Chalarangelo/30-seconds-of-code
February 8, 2024 - We can then use String.prototype.lastIndexOf() to find the last occurrence of the match in the string. If a match is found, we can use String.prototype.slice() and a template literal to replace the matching substring with the given replacement.
Author: Chalarangelo
🌐
The Web Dev
thewebdev.info › home › how to replace the last occurrence of a character in a string in javascript?
How to Replace the Last Occurrence of a Character in a String in JavaScript? - The Web Dev
September 2, 2022 - To replace the last occurrence of a character in a string in JavaScript, we can use the JavaScript string replace method with a regex.
🌐
xjavascript
xjavascript.com › blog › javascript-replace-last-occurrence-of-text-in-a-string
JavaScript: How to Replace Last Occurrence of Text in a String – Complete Guide
For example: ... The first "banana" remains, but the last one is replaced. JavaScript’s native replace() method with str.replace("banana", "grape") only replaces the first occurrence, and str.replace(/banana/g, "grape") replaces all.
🌐
W3Schools
w3schools.com › jsref › jsref_lastindexof.asp
JavaScript String lastIndexOf() Method
at() charAt() charCodeAt() codePointAt() concat() constructor endsWith() fromCharCode() includes() indexOf() isWellFormed() lastIndexOf() length localeCompare() match() matchAll() padEnd() padStart() prototype repeat() replace() replaceAll() search() slice() split() startsWith() substr() substring() toLocaleLowerCase() toLocaleUpperCase() toLowerCase() toString() toUpperCase() toWellFormed() trim() trimEnd() trimStart() valueOf() JS Typed Arrays
🌐
LabEx
labex.io › labs › javascript-replace-last-occurrence-in-string-28594
Replace Last Occurrence in String | LabEx
Learn how to use the replaceLast function to efficiently replace the last occurrence of a pattern in a string.