Getting substring in jQuery by substring and substr methods
Using substring method in jQuery
In series of JavaScript tutorials, I explained with examples how you can use the substring and substr methods to get substrings.
As such, the jQuery is the library of JavaScript; you can use these methods in jQuery as well to get the substrings.
See the following examples of using substring and substr functions in jQuery code.
An example of jQuery substring method with paragraph text
In this example, a string is created by using the $.text method of jQuery where paragraph text is assigned to a variable. After that, the substring method is used to create a substring by using both parameters; start and end indices.
The substring is displayed in a div element by using the $.append method of jQuery. All that code is placed at the click event of the button.
See online demo and code
As you click the button, the following jQuery code is executed:
1 2 3 4 5 6 7 8 9 10 11 |
$(".btncls").click(function(){ var source_string = $( ".stringpara" ).text(); var str_sub = source_string.substring(7,37); $(".substringdiv").append(str_sub); }); |
An example of substr method to get substring
Now, the same string as in above example except using the substr method to get the substring. As such, the substr method also takes two parameters, start index and length of the substring, I am using both in this example. See the example online by clicking the link or image below.
See online demo and code
This jQuery code is used to execute the substr method at the click event of button:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<script> $(document).ready(function(){ $(".btncls").click(function(){ var source_string = $( ".stringpara" ).text(); var str_sub = source_string.substr(11,23); $(".substringdiv").append(str_sub); }); }); </script> |
See the complete code with markup and style in the demo page.