The JavaScript string match() method matches the string against a regular expression. This method returns an array with the matches and null if no match is found.
string.match(match)
str.match(regexp)
JavaScript string match
A simple example code search for “red” using a string with a regular expression and other examples do a 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:
- If the
regexp
uses theg
flag, thenmatch()
method returns an array containing all the matches. The result does not include the capturing groups. - If the
regexp
doesn’t use theg
flag, thematch()
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