We saw a few examples for substring() in this post.
Let’s understand how substr() works.
substr() method in JavaScript
Syntax
string.substr(from, numberOfCharacters)
Things to remember
- The from argument is the position you want to start the substring from and numberOfCharacters argument is the total number of characters you want to take out.
- from is required and numberOfCharacters is optional. If you don’t specify numberOfCharacters then it will give you the rest of the string in return from the specified starting index.
- First character starts at zero and if we specify from greater or equal to the number of characters in the string then it will return an empty string.
- If from is negative then it will use it as an index from the end of the string.
Examples
Get first 6 characters from a string using substr()
var str = "YogeshChauhan.com";
var sub = str.substr(0,6);
console.log(sub);
//Yogesh
Get the rest of the string skipping the first 6 characters using substr()
var str = "YogeshChauhan.com";
var sub = str.substr(6);
console.log(sub);
//Chauhan.com
Get the first character from the string using substr()
var str = "YogeshChauhan.com";
var sub = str.substr(0,1);
console.log(sub);
//Y
Get the last character from the string using substr()
var str = "YogeshChauhan.com";
var sub = str.substr(str.length-1,1);
console.log(sub);
//m
The difference between substring() and substr()
The substr() method takes out parts of a string just like substring() does. The subtle difference is in the way it works and how it works.
substring() takes two arguments, start and end for the substring you want. substr() takes two arguments too and the first argument is the start of the substring as well. The only difference is the second argument we pass. In substr() we need to pass the number of characters we want in a substring.
difference functions JS Methods method substring