We can use the substring() method to extract characters from a string.
It takes two arguments, start and end for the substring you want. It does NOT include the end character.
If you pass the start parameter which is greater than the end parameter then JS will act smart and will swap the parameters.
This method does NOT change the original string but returns a new small(sub) string.
substring() Method syntax
str.substring(from, to)
from argument is the first character to start the substring from and the to argument is the character before the substring ends.
from is required and to is optional.
If you don’t specify the to argument then it will cut the string from the specified from to the end of the string.
It’s a but confusing as why would you want the the first specified character to include and the second one to exclude! But that’s the way it is.
substring() Method return value
substring() method returns a substring. It doesn’t modify the main string.
substring() Method Examples
How to get the first 6 characters from a string?
var str = "YogeshChauhan.com";
var sub = str.substring(0, 6);
console.log(sub);
//Yogesh
How to get the rest of the string skipping the first 6 characters?
var str = "YogeshChauhan.com";
var sub = str.substring(6);
console.log(sub);
//Chauhan.com
How to get the first character from a string?
var str = "YogeshChauhan.com";
var sub = str.substring(0, 1);
console.log(sub);
//Y
How to get the last character from a string?
var str = "YogeshChauhan.com";
var sub = str.substring(str.length - 1, str.length);
console.log(sub);
//m
How to get the last 3 characters from a string?
var str = "YogeshChauhan.com";
var sub = str.substring(str.length - 3);
console.log(sub);
//com
examples functions JS Methods method substring