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.
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: ""
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:
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.