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>
it is helpful, thanks
good work
it worked,
thanks
Works great – thank you.