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

"Text".indexOf('x');

This would result in the following output:

2

Some other examples of the indexOf() method are below:

var text = "Example text";
var str1 = text.indexOf('e');
var str2 = text.indexOf('E');
var str3 = text.indexOf('text');
var str4 = text.indexOf('q');
var str5 = text.indexOf('e',2);
var str6 = text.indexOf('Example');
var str7 = text.indexOf('Examples');

Which would result in the following:

6
0
8
-1
6
0
-1

The main things to remember with the JavaScript indexOf method are that the first character starts at index 0, not 1 and that the characters are case-sensitive.

An example using the JavaScript indexOf Method

Below is an example of replacing an image using JavaScript indexOf() 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 JavaScript indexOf 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.indexOf('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.indexOf('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 JavaScript indexOf() method.

Categorized in:

JavaScript,

Last Update: March 22, 2024