Skip to content
the poor coder

js replace last occurrence of string

Poor Man
Published
Reading time
2 min read
On this page

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.

Text
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.

Text
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.

Text
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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC