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
廣告