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

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 106
    Comment on it

    JavaScript String slice() method : The slice() method is used to extract the sub-string. The index is starts from 0. To return the string from last position use negative index.

    Syntax of slice() method :

    string.slice(start,end)
    

    start : This is required parameter. This is the start index of the string and returns the string started from this point.

    end : This is optional parameter. This is the end point and the slice method trim the string upto this point.


    Example of the slice() method : Following are some examples shows the uses of slice() method.

    Example1.html

    <!-- Shows how can extract the string from given point. -->
    
    <!DOCTYPE html>
    <html>
    <body>
    
    <p>Click on button to see the extracted string.</p>
    <button onclick="sliceString()">slice</button>
    <p id="container"></p>
    
    <script>
    function sliceString() {
        var msg = "Hello! Welcome here."; 
        var res = msg.slice(5);
        document.getElementById("container").innerHTML = res;
    }
    </script>
    
    </body>
    </html>
    
    Output : ! Welcome here.
    

    Example2.html

    <!-- Display the part of string between two points. -->
    <!DOCTYPE html>
    <html>
    <body>
    
    <p>Click on button to see the extracted string.</p>
    
    <button onclick="sliceString()">slice</button>
    
    <p id="container"></p>
    
    <script>
    function sliceString() {
        var str = "Hello! Welcome here."; 
        var res = str.slice(5, 14);
        document.getElementById("container").innerHTML = res;
    }
    </script>
    
    </body>
    </html>
    
    Output : ! Welcome
    

    Example3.html

    <!-- To display the last character use negative index-->
    <!DOCTYPE html>
    <html>
    <body>
    
    <p>Click on button to see the extracted string.</p>
    <button onclick="sliceString()">slice</button>
    <p id="container"></p>
    
    <script>
    function sliceString() {
        var str = "Hello! Welcome here!"; 
        var res = str.slice(-1);
        document.getElementById("container").innerHTML = res;
    }
    </script>
    
    </body>
    </html>
    
    Output :     !
    

 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: