Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • substr() method in JavaScript String

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 154
    Comment on it

    JavaScript String substr() method : The substr() method is used to extract the sub-string from a string. It counts the index from 0. It returns the number of characters starts from the first parameter upto second parameter if passed. It doesn't modify the original string.

    Syntax of substr() method :

    string.substr(start,length)
    

    start : This is required parameter. This is the numeric index from where the method starts the extract substring.

    end : This is optional parameter. This is also numeric and define the number of characters need to extract.


    Example of substr() method : Following are the examples showing how we can use the substr() method.

    Example1.html

    <!-- Here we use the method with single parameter-->
    
    <!DOCTYPE html>
    <html>
    <body>
    <p>To display the substring, press the button.</p>
    <button onclick="showSubstring()">substring</button>
    <p id="container"></p>
    
    <script>
    function showSubstring() {
        var str = "I am happy today.";
        var result = str.substr(2);
        document.getElementById("container").innerHTML = result;
    }
    </script>
    
    </body>
    </html>
    
    Output :  am happy today.
    

    Example2.html

    <!-- Here we use the method with two parameters with setting 8 characters limit-->
    
    <!DOCTYPE html>
    <html>
    <body>
    <p>To display the substring, press the button.</p>
    <button onclick="showSubstring()">substring</button>
    <p id="container"></p>
    
    <script>
    function showSubstring() {
        var str = "I am happy today.";
        var result = str.substr(2, 8);
        document.getElementById("container").innerHTML = result;
    }
    </script>
    
    </body>
    </html>
    
    Output :  am happy
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: