JavaScript 字符串 match() 方法
JavaScript 字符串的 match() 方法在原始字符串中搜索一个字符串或正则表达式,并返回包含所有匹配项的数组。如果未找到匹配项,则返回 Null。如果搜索值是字符串,则将其转换为正则表达式并开始搜索。
如果将正则表达式传递给 match() 方法,并使用 'g'(全局)标志,则将返回所有与完整正则表达式匹配的结果;但如果未使用 'g' 标志,则仅返回第一个完整匹配项及其相关的捕获组。
语法
以下是 JavaScript 字符串 match() 方法的语法 -
match(regexp)
参数
- regexp - 一个 regexp(正则表达式)对象。
返回值
此方法返回一个包含所有正则表达式的数组。匹配。
示例 1
如果在原始字符串中找到匹配项,则返回一个包含匹配项的数组。
在下面的示例中,我们使用 JavaScript 字符串的 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"。
Original string: Hi how are you? 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"。
Original string: JavaScript is a scripting langauge 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"。
Original string: JavaScript is a scripting langauge 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 = "TutorialsPoint";
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"。
Original string: TutorialsPoint Regexp: /tuto/g An array with all matches: null

