We can use the String lastIndexOf JavaScript method to get the last position of a value (string or character) within a string. If the value is not found within the string, -1 is returned.

"Text".lastIndexOf('x');

This would result in the following output:

2

Some other examples of the lastIndexOf JavaScript method are below:

var text = "This text is some Example text";
var str1 = text.lastIndexOf('e');
var str2 = text.lastIndexOf('E');
var str3 = text.lastIndexOf('text');
var str4 = text.lastIndexOf('t');
var str5 = text.lastIndexOf('Example');
var str6 = text.lastIndexOf('Examples');

Which would result in the following:

str1 = 27
str2 = 18
str3 = 26
str4 = 29
str5 = 18
str6 = -1

The main things to remember with the lastIndexOf() method are that the first character starts at index 0, not 1, and that it is case-sensitive.

An example using the lastIndexOf JavaScript Method

Below is an example of replacing an image using lastIndexOf and other JavaScript methods.

Change image

Let’s say we have another image called “example-img2” which is in the same location as the image above. When we click the button, we want to swap out that image. We will use the lastIndexOf JavaScript method to get the location of “example-img1” and use the substring() method to get the first part of the image location. Then we will add the new image file name and replace the old image. Here is the JavaScript code below:

$("#click-me").click(function(){
  var oldImgAddress = $('#img1').attr('src');
  var indexOfImage = oldImgAddress.lastIndexOf('example-img1.png');
  var firstPartOfString = oldImgAddress.substring(0,indexOfImage);
  var newImgAddress = firstPartOfString + "example-img2.png"; // we add the new file name to the end of the string
  //This new string should now be "https://daztech.com/wp-content/uploads/example-img2.png"
  //We can now use jQuery to replace the old image  
  $('#img1').attr('src',newImgAddress);
});

The final code and output for this example is below:

Code Output:

Change image

Full Code:

Change image


<script>

$("#click-me").click(function(){
  var oldImgAddress = $('#img1').attr('src');
  var indexOfImage = oldImgAddress.lastIndexOf('example-img1.png');
  var firstPartOfString = oldImgAddress.substring(0,indexOfImage);
  var newImgAddress = firstPartOfString + "example-img2.png";
  $('#img1').attr('src',newImgAddress);
});

</script>

Hopefully this article has been useful in helping you understand the String lastIndexOf() JavaScript method.

Categorized in:

JavaScript,

Last Update: May 3, 2024