Last updated on
If you’re looking for a jQuery substring function then stop looking!
Like the jQuery if statement – it doesn’t exist.
Using substr to get a jQuery substring
var $someText = $('#name').val(); // Let's say this gets the value 'James Bubb' var firstName = $someText.substr(0,5); // firstName now has the value 'James' var secondName = $someText.substr(6,4) // secondName now has the value 'Bubb'
If you haven’t used it before, substr works by taking 2 parameters: start position, and length.
So, to get the first name from the string we start at position 0 (as the string, like an array, is zero-indexed) and then we get the next 5 letters.
To get the second name we start at position 6 in the string (missing the space) and then get the next 4 letters.
Using substring to get a jQuery substring
It does pretty much the same thing as substr but with a subtle difference. See if you can spot it.
var $someText = $('#name').val(); // Let's say this gets the value 'James Bubb' var firstName = $someText.substr(0,5); // firstName now has the value 'James' var secondName = $someText.substr(6,10) // secondName now has the value 'Bubb'
Did you spot the differenence?
Whereas the second parameter of substr is the length of the sub string you want to return, with substring the second parameter is the end point.
Therefore, when getting the secondName we need to specify the the point at which the string ends.
Use either substr or substring with a jQuery reference to achieve a jQuery substring.
$someText.substr(start, length) $someText.substring(start, end)