js replace last occurrence of string

JavaScript: Replace Last Occurrence of String

Replacing the last occurrence of a string in JavaScript can be a bit tricky. It requires careful use of string manipulation methods to achieve the desired result.

Method 1: Split and Join

One way to replace the last occurrence of a string is to split the original string into an array, replace the last element of the array with the new value, and then join the array back into a string.

let str = "hello world, hello again";
let last = str.lastIndexOf("hello");
let arr = str.split("");
arr[last] = "goodbye";
str = arr.join("");
console.log(str); // "hello world, goodbye again"

Method 2: Regular Expressions

Another way to replace the last occurrence of a string is to use a regular expression with a negative lookahead.

let str = "hello world, hello again";
let regex = /hello(?!.*hello)/;
str = str.replace(regex, "goodbye");
console.log(str); // "hello world, goodbye again"

This regular expression matches "hello" only if it is not followed by any other occurrences of "hello".

Method 3: Reverse and Replace

Yet another way to replace the last occurrence of a string is to reverse the original string, replace the first occurrence of the reversed substring, and then reverse the resulting string.

let str = "hello world, hello again";
let rev = str.split("").reverse().join("");
let sub = "olleh".split("").reverse().join("");
let newSub = "eybdoog".split("").reverse().join("");
rev = rev.replace(sub, newSub);
str = rev.split("").reverse().join("");
console.log(str); // "hello world, goodbye again"

Conclusion

These are just a few ways to replace the last occurrence of a string in JavaScript. Depending on your specific use case, one method may be more appropriate than another.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe