The substr() method and the substring() method of Javascript is quite used but also there is quite good confusion regarding both of them and in this tutorial, i am gonna talk about javascript substr() and substring() method from bare basics

substr()

The substr() method is a way to play with a string or more specifically a way to return a certain part of a string as we have in splice() if you don’t know splice() i recommend have a look at MDN DOCS

susbstr() method takes 2 arguments to work first is the index and second is the no. of characters after that index

Maybe you can understand it better by understanding the example below

let string = "Hi I am felling Sleepy really :} "

console.log(string.substr(3,19));

As you can see i want to start from I which is on 3rd index the Index in string work as same as in array so it doesn’t make much hassle after that i just want to get it till Sleepy which is after 19 characters

Maybe Now you got it if not Let’s have a look at one more example

let string = "Hi This Tutorial is good  ";

console.log(string.substr(3,23))

Now maybe you get it

The starting or ending for substr

As you might get the understanding of substr to let’s assume that you want to start capturing index from the end instead of the beginning there is a solution for it as well

actually this problem of ours is solved by javascript already as when you pass the index with positive it starts with the beginning of the string but when you give a negative value of index it starts with the end

Let’s have a look at it so you can understand it a lot better

//To GET FROM START//
let string = "ABCDEFGHIJKL";

console.log(string.substr(3,5));

//OUTPUT//
//DEFGH//

//BECAUSE NOW IT STARTS FROM D //
//To GET FROM END//
let string = "ABCDEFGHIJKL";

console.log(string.substr(-3,5));

//OUTPUT//

//JKL//

//BECAUSE NOW IT STARTS FROM -3 form END that's why printed JKL //

Now maybe you got both of these now let’s talk about substring()

The substring()

The substring() method is also similar to slice() and we can substr() as well but there is a difference as well that it doesn’t accept negative values it can have 2 parameters the first is the index and the second optional parameter is the indicator where to end the string

Quite simple and i don’t think more to explain it

Let’s directly move towards the examples to understand it better

//To GET FROM END//
let string = "Javascript is super great";

console.log(string.substring(3,10));

//OUTPUT//

//ascript//

Now maybe this is clear to you and they’re different as well

Wrapping UP

So now maybe you get this if you liked this tutorial you can check out other tutorials of mine here if you loved this tutorial all queries questions and appreciations are always welcome as you know LOL :} :}