How to substring in jQuery

Well, Substring is not a unknown term for all of us. Substring means to take out some part from the string. And to do Substring with jQuery, you don't have to do anything specific with jQuery. It can be done with two Javascript functions substr() and substring() which can be easily used in jQuery. We will see both the functions.

Earlier I had posted about jQuery solution to replace string, split string, trim string and about all string functions, And In this post, see jQuery/JavaScript substring function in action with example.

substring()

The syntax of substring function is as follow.
string.substring(from, to);
It takes 2 parameters.
  • from: This parameter is required. It denotes the index where to start the substring. Remember the index starts with 0 in Javascript.
  • to: This parameter is optional. It denotes the index where to stop the extraction. If not passed then it extracts the rest of the string.
$(document).ready(function(){
    var str = 'jQuery By Example';
    $('#spnBeforeSubstring').html(str);
    $('#spnAfterSubstring').html(str.substring(2,12));
});​
In above jQuery code, the substring() function start extracting from 2nd character and goes up to 12th character. So it will return 10 characters from the string.

See result below.



substr()

The syntax of substring function is as follow.
string.substr(start,length);
It takes 2 parameters.
  • start: This parameter is required. It denotes the index where to start the substring. Remember the index starts with 0 in Javascript.
  • length: This parameter is optional. It denotes the number of characters to extract. If not passed then it extracts the rest of the string.
$(document).ready(function(){
    var str = 'jQuery By Example';
    $('#spnBeforeSubstring').html(str);
    $('#spnAfterSubstring').html(str.substr(2,12));
});​
In above jQuery code, the substr() function start extracting from 2nd character and it will count 12 characters from 2nd character. That means it will return 12 characters.

See result below.



You must have got the idea about the differences between these 2 functions. They only differ with their parameters. You can use any function as per your wish. Previously there was an issue with substr(), that it was not cross browser. But now all the modern browsers supports both the functions.

Feel free to contact me for any help related to jQuery, I will gladly help you.
SHARE

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..