Different ways of using Javascript substring

There are so many situations where we have to subtract a string out of a large string or in some situations we have to extract a small piece of string from a bigger word or string. For this Javascript have a function of substring() which returns the part of the string between the start and ending index. Let’s start from an example before we go into more details

const str = 'DevLizards.com';

console.log(str.substring(3)); // 3 is starting point
// expected output: "Lizards.com"
const str = 'DevLizards.com';

console.log(str.substring(3,6)); // 3 is starting point and 6 is ending point
// expected output: "Liz"

You can also use the length property with it:

const str = "DevLizards.com";

const len = str.length;
console.log(str.substring(len - 4))
// expected output: ".com"

Now from the above examples, you can see that how easy it is to extract a small piece of string from the given string. This function automatically converts the string letters into an array and loops through each one of them to show us the start and the end and make a substring.

The first parameter is always required which is the starting point. The second parameter is optional which is the ending point.

Difference Between Javascript substring and Javascript slice:

Both of these methods are almost identical except there are a few differences for example if starting index is greater than the ending index in the substring, it will swap it and take the small value as starting index and large as the ending index, if the same situation is with slice method, it will return an empty string.
Let’s view an example:

const str = "DevLizards.com";


console.log(str.substring(6,2))
// expected output: "vLiz"

console.log(str.slice(6,2))
// expected output: ""

Let’s see another example with a negative value:

console.log(str.substring(-6,2))
// expected output: "De"

console.log(str.slice(-6,2))
// expected output: ""

difference between JavaScript substring and substr:

Although both methods return part of the string but there is some differences between them. In substring we give start index and end index to get the part of the string but in the substr, we provide start index and the maximum length of the string to extract. Basic syntax is below:

substr(index, length)

Let’s look at one example which shows a difference between both of them.

var str = "hello lizards";
console.log(str.substr(5, 8));
// Return : lizards

if you don’t add the length, by default it will return the remaining part of the string.