JavaScript - match() method

revision:


Category : string

The match() method matches a string against a regular expression. The match() method returns an array with the matches or it returns null if no match is found.

If the search value is a string, it is converted to a regular expression.

Syntax :

        string.match(match)
    

Parameters:

match : required. The search value. A regular expression (or a string that will be converted to a regular expression).

Examples:

        <p>match() searches for a match in a string.</p>
        <p>Do a search for "ain":</p>
        <p id="demo"></p>
        <script>
            let text = "The rain in SPAIN stays mainly in the plain";
            let result = text.match("ain");
            document.getElementById("demo").innerHTML = result;
        </script>
    

Practical examples

example: a search for "ain" using a string or regular expression.

Do a search for "ain":

code:
                    <div>
                        <p>Do a search for "ain":</p>
                        <p id="match-1"></p>
                        <p id="match-2"></p>
                        <p id="match-3"></p>
                        <p id="match-4"></p>
                        <p id="match-5"></p>
                    </div>
                    <script>
                        let text = "The rain in SPAIN stays mainly in the plain";
                        document.getElementById("match-1").innerHTML = "text : " + text;
                        let result = text.match("ain");
                        document.getElementById("match-2").innerHTML = "string - result : " + result;
                        let result1 = text.match(/ain/);
                        document.getElementById("match-3").innerHTML = "regular expression - result : " + result1;
                        let result2= text.match(/ain/g);
                        document.getElementById("match-4").innerHTML = "regular expression/g - result : " + result2;
                        let result3= text.match(/ain/gi);
                        document.getElementById("match-5").innerHTML = "regular expression/gi - result : " + result3;
                    </script>