jQuery substring: How to get part of a string using jQuery

Learn how to create substrings of other strings with jQuery.

If you’re looking for a jQuery substring function then stop looking! Like the jQuery if statement - it doesn’t exist. What you can do however is use native JavaScript tools to work with a jQuery substring.

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'

This is a very simplistic example but demonstrates that once you have got the value of an element (or it could be its innerText / innerHTML if it’s not a form element) you can use normal JavaScript to work with it. If you’re not familiar with the JavaScript substr function then the above will make sense to you. 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

There’s also a different function in JavaScript called 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.

Conclusion

Use either substr or substring with a jQuery reference to achieve a jQuery substring.

$someText.substr(start, length)
$someText.substring(start, end)