JavaScript – Replace Last Occurrence of a String

The below code example shows you the way to replace the last occurrence of a string in JavaScript.

 

1. Implementation

string-example.js
function replaceLast(find, replace, string) {
    var lastIndex = string.lastIndexOf(find);
    
    if (lastIndex === -1) {
        return string;
    }
    
    var beginString = string.substring(0, lastIndex);
    var endString = string.substring(lastIndex + find.length);
    
    return beginString + replace + endString;
}

 

2. Usage and Example 

Here is an example that shows how to use the implemented function above. Click on the “Run Example” button to see how it works.

example.htmlRun Example
<!DOCTYPE html>
<html>
<head>
    <title>JavaScript – Replace Last Occurrence of a String</title>
</head>
<body>
    <h3>Results:</h3>
    <p id="result1"></p>
    <p id="result2"></p>


    <script type="text/javascript">
        function replaceLast(find, replace, string) {
            var lastIndex = string.lastIndexOf(find);
            
            if (lastIndex === -1) {
                return string;
            }
            
            var beginString = string.substring(0, lastIndex);
            var endString = string.substring(lastIndex + find.length);
            
            return beginString + replace + endString;
        }

        // example 1
        var str1 = "Hello World-";
        var newStr1 = replaceLast("-", "", str1);
        document.getElementById('result1').innerHTML = newStr1;

        // example 2
        var str2 = "Foo and Bar. Hello Bar";
        var newStr2 = replaceLast("Bar", "guys", str2);
        document.getElementById('result2').innerHTML = newStr2;
    </script>

</body>
</html>

0 0 vote
Article Rating
guest
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Alex Rybak
Alex Rybak
2 years ago

it is helpful, thanks

Erwind
Erwind
2 years ago

good work

Sagar Kharab
Sagar Kharab
2 years ago

it worked,
thanks

3
0
Would love your thoughts, please comment.x
()
x