var NewSubstring = NewSubstring.substring(StartingPosition, EndPosition)
NewSubstring is any string. StartingPosition and EndPosition are both integers between 0 and NewSubstring.length – 1. StartingPosition is the index of the first character in the substring, whereas EndPosition is the index of the last character in the substring plus 1. The following script assigns the string “computer” to the variable segment:
Character Position 0 1 2 3 4 5 6 7 8 9 10 11 12 13 Character e c o m p u t e r n o t e s
We’ll be covering the following topics in this tutorial:
var myStr = new String("ecomputernotes"); alert(myStr.substring(9)); // alerts 'notes' alert(myStr.substring(0)); // alerts 'ecomputernotes' alert(myStr.substring(0, 9)); // alerts 'ecomputer'
Two scenarios come to mind with the arguments that substring() takes. First, What happens if the first argument is bigger than the second argument? This is handled very ‘neatly’: they’re reversed. Every time substring() sees two arguments, it will always consider smaller number to be the first argument. So, in a sense, if you give substring() two arguments, it doesn’t matter in what order you place them… substring() will ‘make it work’ for you (in a sense).
The second scenario is negative numbers. The substring() method handles negative numbers very simply: every number less than 0 equals 0. Again, very ‘neat’, isn’t it? If substring() sees that any argument that was given to it is less than 0, then it will convert it to 0.
I should be clear that my writing ‘neat’ and ‘neatly’ isn’t me being snarky, it’s the purpose of the substring() method to automatically ‘avoid problems’ when you choose to use it, as opposed to the slice() method which will consider every option, and, as a result, will allow many unwanted results if you choose to use it in the ‘wrong’ place. But we’ll get to slice() in a bit.
var myStr = new String("ecomputernotes"); alert(myStr.substring(-9)); // alerts 'ecomputernotes' alert(myStr.substring(-3, 9)); // alerts 'ecomputer' alert(myStr.substring(9, -5)); // alerts 'ecomputer'
The first one is converted to one argument, ‘0’, and so returns the entire String. The second is converted to substring(0, 9), and so returns ‘ecomputer’. The third is first converted to substring(3, 0), and the arguments are reversed into: substring(0, 9), so you get: ‘ecomputer’.