JavaScript String match() 方法在原始字符串中搜索字符串或正则表达式,并返回包含所有匹配项的数组。如果未找到匹配项,则返回 Null。如果搜索值是字符串,则会将其转换为正则表达式并开始搜索。
如果将正则表达式传递给 match() 方法,并使用 'g'(global) 标志,则将返回与完整正则表达式匹配的所有结果,但如果未使用 'g' 标志,则仅返回第一个完整匹配及其相关的捕获组。
语法
以下是 JavaScript String match() 方法的语法 -
match(regexp)
参数
- regexp − 一个 regexp(正则表达式)对象。
返回值
此方法返回一个包含所有匹配项的数组。
示例 1
如果在原始字符串中找到匹配项,则返回一个包含匹配项的数组。
在下面的示例中,我们使用 JavaScript String match() 方法搜索字符串 'h' 并检索包含原始字符串 “Hi how are you?” 中所有匹配项的数组
<html>
<head>
<title>JavaScript String match() Method</title>
</head>
<body>
<script>
const str = "Hi how are you?";
let search_str = "h";
document.write("Original string: ", str);
document.write("<br>Search string: ", search_str);
document.write("<br>An array with all matches: ", str.match(search_str));
</script>
</body>
</html>
输出
上面的程序返回 'h'。
Search string: h
An array with all matches: h
示例 2
当我们全局搜索正则表达式 '/src/g' 时。
以下是 JavaScript match() 方法的另一个示例。在这里,我们使用此方法在原始字符串 'JavaScript is a scripting language' 中全局搜索正则表达式 '/src/g',并尝试检索具有匹配项的数组。
<html>
<head>
<title>JavaScript String match() Method</title>
</head>
<body>
<script>
const str = "JavaScript is a scripting langauge";
let regexp = /scr/g;
document.write("Original string: ", str);
document.write("<br>Regexp: ", regexp);
document.write("<br>An array with all matches: ", str.match(regexp));
</script>
</body>
</html>
输出
执行上述程序后,将返回 “src”。
Regexp: /scr/g
An array with all matches: scr
示例 3
当我们全局搜索正则表达式 '/src/gi' 且不区分大小写时。
在这个程序中,我们使用 JavaScript 字符串 search() 方法在原始字符串 “JavaScript is a scripting language” 中全局搜索正则表达式 '/src/gi' ,不区分大小写,并尝试检索一个包含所有匹配项的数组。
<html>
<head>
<title>JavaScript String match() Method</title>
</head>
<body>
<script>
const str = "JavaScript is a scripting langauge";
let regexp = /scr/gi;
document.write("Original string: ", str);
document.write("<br>Regexp: ", regexp);
document.write("<br>An array with all matches(global case-insensitive): ", str.match(regexp));
</script>
</body>
</html>
输出
上面的程序返回 “Src, src”。
Regexp: /scr/gi
An array with all matches(global case-insensitive): Scr,scr
示例 4
如果未找到匹配项,则 match() 方法将返回 null。
<html>
<head>
<title>JavaScript String match() Method</title>
</head>
<body>
<script>
const str = "QikepuCom";
let regexp = /tuto/g;
document.write("Original string: ", str);
document.write("<br>Regexp: ", regexp);
document.write("<br>An array with all matches: ", str.match(regexp));
</script>
</body>
</html>
输出
执行上述程序后,它将返回 'null'。
Regexp: /tuto/g
An array with all matches: null