To get a substring from a string in JavaScript, we can use the substring() method.


This would result in the following output:


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

var text = "Example text";
var str1 = text.substring(0,3);
var str2 = text.substring(1,4);
var str3 = text.substring(3);
var str4 = text.substring(3,0);
var str5 = text.substring(0);

Which would result in the following:

mple text
Example text

The main things to remember with the JavaScript substring method are that the first number is the start position and the first character starts at index 0, not 1. And then the only other tricky part is that the last number is the end position of the string, not including that number. We find it easiest to learn how the substring method works by just trying out a bunch of examples, as seen above.

An example using the JavaScript Substring Method

Below is an example of replacing an image using JavaScript substring() 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. This can be useful when we have images in order of img1, img2, im3, etc… So we will use the JavaScript substring method to get the image location. Then we will use the indexOf and substring methods to build the new image link. And finally, we will replace the old image. Here is the JavaScript code below:

  var oldImgAddress = $('#img1').attr('src');
  //Since we know the image will have the same address, we just need to change the number from "example-img1" to "example-img2". To do this we will find the indexOf the number "1", and then build a new string using this information.
  var index1 = oldImgAddress.indexOf('1');
  var firstPartOfString = oldImgAddress.substring(0,index1); //This will get the all the characters before "1";
  var lastPartOfString = oldImgAddress.substring(index1+1); //This will get all the characters after "1";
  //We then just have to add in "2" between the two strings;
  var newImgAddress = firstPartOfString + "2" + lastPartOfString;
  //This new string should now be ""
  //We can now use jQuery to replace the old image  

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 index1 = oldImgAddress.indexOf('1'); var firstPartOfString = oldImgAddress.substring(0,index1); var lastPartOfString = oldImgAddress.substring(index1+1); var newImgAddress = firstPartOfString + "2" + lastPartOfString; $('#img1').attr('src',newImgAddress); }); </script>

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

Categorized in:


Last Update: March 1, 2024