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

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 122
    Comment on it

    JavaScript String match() method : We use match() method to match a string against a regular expression. It returns the array object of strings which matched if used with the /g modifier otherwise it returns the first matched string. It returns null if no match found.

    Syntax of match() method :

    string.match(regexp)
    


    The match() method can be used with the following two modifiers :

    1. /regEx/g : modifier '/g' is used as a global search, means it will returns all the strings which matched in the form of array of string.
      Syntax :

      string.match(regexp/g)

    2. /regEx/gi : modifier '/gi' is used when we want to perform non case sensitive search. This will also return the array of matched strings.
      Syntax :

      string.match(regexp/gi)


    Example of match() method : Following is the example of match() method, In first example I will show you case sensitive search and in the second example case-insensitive search.

    Example1.html

    <!DOCTYPE html>
    <html>
    <body>
    <p>To see the matches click on the button.</p>
    <button onclick="matchString()">Check</button>
    <p id="container"></p>
    
    <script>
    function matchString() {
        var str = "His name is RISHABH."; 
        var result = str.match(/is/g);
        document.getElementById("container").innerHTML = result;
    }
    </script>
    </body>
    </html>
    
    Output : is,is
    

    In the above example we can see that two matches found for string is, because this is case sensitive search so it ignores the IS.


    Example2.html

    <!DOCTYPE html>
    <html>
    <body>
    
    <p>To see the matches click on the button.</p>
    <button onclick="matchString()">Check</button>
    <p id="container"></p>
    <script>
    function matchString() {
        var str = "His name is RISHABH."; 
        var result = str.match(/is/gi);
        document.getElementById("container").innerHTML = result;
    }
    </script>
    </body>
    </html>
    
    Output : is.is,IS
    

    As above example shows result is include the case-insensitive result for is and result the 'IS.


 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: