Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Extracting a part of string in JavaScript

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 395
    Comment on it

    Hello Readers,

     

    In today's post we will discuss about the how we can extract the part of a string in JavaScript. These methods make easy to deal with strings.

     

    To extract the part of a string there are three methods which are as follows:

     

    • slice() method: slice() method used to take out the part of a string and returns the rest of the part. In this method we need to pass two parameters. First one is for starting position pf the string and the second one is for ending position of the string.

     

    For Example:

    var str = "India is a beautiful country";
    var sliceStr = str.slice(11,21);
    console.log(sliceStr); // Returns beautiful

     

    If we pass the negative parameter in the method it will count the position from the end of the string.

     

    For Example:

    var str = "India is a beautiful country";
    var sliceStr = str.slice(-17, -8);
    console.log(sliceStr); // Returns beautiful

    In the above example the method extracts the string from position -17 to -8.

     

    If we will pass only one parameter then it will extract the rest of the string.

     

    For Example:

    var str = "India is a beautiful country";
    var sliceStr = str.slice(11);
    console.log(sliceStr); // Returns beautiful country

     

    var str = "India is a beautiful country";
    var sliceStr = str.slice(-17);
    console.log(sliceStr); // Returns beautiful country

     

    • substring() method:  This method is similar to slice() method. The only difference is substring() method doesn't work with negative positions.

     

    • substr() method: This method is same as slice() method. We need to pass two parameters like slice() method but the only difference is the second parameter indicate the length of separated part.

     

    For Example:

    var str = "India is a beautiful country";
    var myString = str.substr(11,10);
    console.log(myString); // Returns beautiful

     

    Note: The first parameter can be in negative then the position will count from the end of the string but second parameter can't be negative as it specifies the length of the string. 

     

    Hope this will help you :)

     

     

 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: