Jquery Substring

jQuery Substring is a jquery plugin that allows you to extract the text from inside a string. This can be used for many purposes, such as extracting an email address from a string of words and numbers. To use jquery substring, all you have to do is pass in the string of text and it will return the substrings found within it!

How to use jQuery Substring:

JQuery is an awesome library that lets you easily manipulate and control JavaScript. You can use the substring() function to extract a sub-string from any string, or as in this example of jQuery code; get just what’s inside your brackets with substr().

$(".btncls").click(function(){ 
var source_string = $( ".stringpara" ).text();
 var str_sub = source_string.substring(7,37);
 $(".substringdiv").append(str_sub);
 });

To extract a piece of text from an object, you have to use the substring() method in jQuery. It has two parameters:

  1. The “from” parameter is useful if you’re looking for certain patterns in arrays or sentences and want them starting at specific indices rather than beginning with 0 (“zero”).
  2. The to a parameter is optional. It specifies the index where to stop extracting words, which if left blank will extract everything from start until the end of the sentence. This lets you make some creative edits in a single line while preserving the original content

Example

<html>

   <head>
      <title>jQuery subtring</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function(){
            $("#button1").click(function(){
              var str1 = "Hello World!";
              var subStr = str1.substring(0, 5);
              alert(subStr);
            });
         });
      </script>
       
   </head>
   
   <body>
     <p>Hello World!</p>
     <button id="button1">Get substring</button>        
   </body>
   
</html>

Example 2:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Strings</h2>

<p>The substring() method extracts parts of a string.</p>

<p id="demo"></p>

<script>
let str = "Hello world!";
document.getElementById("demo").innerHTML = str.substring(1, 4);
</script>

</body>
</html>

Conclusion:

In this blog post, we will review the jQuery Substring method which is used to extract text from a string. This utility can be useful for extracting data in JavaScript and also as an addition to your front-end web development skillset. Let’s get started!

Browser Support

ChromeEdgeFirefoxInternet ExplorerOperaSafariNode.js
Full support 45Full support 12Full support
1
Full support
4
Full support
4
Full support
4
Partial supportPartial

Desktop Browsers

WebView AndroidChrome AndroidFirefox AndroidOpera AndroidSafari on iOSSamsung Internet
Full
support
45
Full
support
45
Full
support
4
Full
support
10.1
Full support
14
Full
support
5.0

Also read: Jquery If Else for Beginners

Follow us on Facebook

Leave a Comment