Skip to content

JavaScript string match() | Method

  • by

JavaScript string match() method is used to match the string against a regular expression. This method method returns an array with the matches and null if no match is found.

string.match(match)
str.match(regexp)

JavaScript string match

Simple example code seach for “red” using a string with regular expression and other example do global search.

<!DOCTYPE html>
<html>
<body>
  <script>
    let text = "Mr. Red has a red house";
    
    let res = text.match("red");
    console.log(res)

    // Using a regular expression
    let out = text.match(/red/);
    console.log(out)

    // Global seach
    let g = text.match(/red/g);
    console.log(g)

    // case-insensitive search
    let all = text.match(/red/gi);
    console.log(all)

  </script>

</body>
</html>

Output:

JavaScript string match Method
  • If the regexp uses the g flag, then match() method returns an array containing all the matches. The result does not contain the capturing groups.
  • If the regexp doesn’t use the g flag, the match() method will return the first match and its related capturing groups.

Using the JavaScript Regex match() method with the named capturing group

let str = 'I like yellow color palette!';

let re = /(?<color>yellow) color/;
let result = str.match(re);

console.log(result);

Do comment if you have any doubts or suggestions on this Js string method tutorial.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *