How to get substring of a string in jQuery?


To get substring of a string in jQuery, use the substring() method. It has the following two parameters:

  • from: The from parameter specifies the index where to start the substring.
  • to: The to parameter is optional. It specifies the index where to stop the extraction. This is an optional parameter, which extracts the remaining string, when nothing is mentioned.

Example

You can try to run the following code to learn how to get substring of a string in jQuery:

Live Demo

<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>

Updated on: 09-Dec-2019

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements