Substr vs Substring in JavaScript

JavaScript has some slick ways of dealing with strings (words, sentences, etc.)  There are a couple of methods in JavaScript called substr() and substring() that do similar but very different things.  Both are able to extract certain parts of a word or sentence to be used or validated.  The difference between them is substr gives a position and how many characters to extract, where substring gives a range of what characters to access.  For example, if we had this:

var str = “SkillForge”;
alert(str.substr(5,3));

This would return “For” because the 5  means start extracting from the 6th character, not the 5th.  Substr and substring start counting at 0 (it’s a JavaScript thing) so when we have 5 in there it actually means the 6th character which is the F in Forge.  Then the 3 tells us to extract three characters from the starting point that was given so that gives us “For”.  If I were to take out the 3 and just have this:

var str = “SkillForge”;
alert(str.substr(5));

It would give us “Forge” because it would start at the 6th letter (5th position) and extract everything until the end of the string.

Now that brings us to substring() which needs a start and end point where substr() just needs a start and how many characters to extract.  So if we had this:

var str = “SkillForge”;
alert(str.substring(2,5));

This would return “ill” from “Skill”.  The 2 tells us where to begin which is the letter “i” and then the 5 tells us how far to go into the string, not how many characters, the ending point.  With substring the end character is NOT included.  So i is the beginning and F is the end and we don’t include that so that ends up giving us “ill”.

Substr and substring are useful with form validation and any other times when we need to take a look at what the user is typing in.  If you want to learn more be sure to check out our web design/development courses.  Have an amazing day!

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *