Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Finding a Substring in a String

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 208
    Comment on it

     Hello reader's in this blog we will discuss finding the substring in a string. When you want to find out a particular series of character in a string we use indexOf method to find out our character.

    The indexOf() method will find out the position of the specified character which exists in the string. If the substring is not found in the given string the value in negative -1 is returned.

     

    Example:-

    var testValue = "This is the test string";
    var subsValue = "test";
    var iValue = testValue.indexOf(subsValue); // returns value of 12, index of substring
    if (iValue != -1) // succeeds, because substring exists

     

    Let's have a look in an example. In the top two line, we have a variable naming "testValue" and "subsValue" which have the string on the first variable and the substring on the second variable. In the third line, we have taken another variable called "iValue", in this line we use indexOf method to find out the substring index. The string indexOf method can return the number which presents the index or position of the character present in the string. In the fourth line, we have a condition for checking if the substring is not found it will return -1. The indexOf method takes two parameters one is  the substring, and other is an optional second parameter is that the index value of where to begin a search.

     

    Syntax:-

    var tstString = "This apple is my apple";
    var iValue = tstString.indexOf("apple", 10);


    The indexOf method works from left to right. There is another method lastIndexOf which can find the sting from right to left, and find the position of the last substring within the string.
     

    Here are some examples you can check in console.

    "This apple is my apple".lastIndexOf("apple");
    Output: It will return the value of 17.

    "This apple is my apple".lastIndexOf("apple",12);
    Output: It will return the value of 5.

     

    Note: The lastIndexOf returns the values based on the starting position.

 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: