當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


JavaScript String match()用法及代碼示例

在本教程中,我們將借助示例了解 JavaScript 字符串 match() 方法。

match() 方法返回將字符串與正則表達式匹配的結果。

示例

const message = "JavaScript is a fun programming language.";

// regular expression that checks if message contains 'programming'
const exp = /programming/;

// check if exp is present in message
let result = message.match(exp);
console.log(result);

/*
Output: [
  'programming',
  index: 20,
  input: 'JavaScript is a fun programming language.',
  groups: undefined
  ]
*/

match() 語法

用法:

str.match(regexp)

在這裏,str 是一個字符串。

參數:

match() 方法包含:

  • regexp - 正則表達式對象(如果參數是非 RegExp 對象,則參數隱式轉換為 RegExp)

注意:如果你不給任何參數,match()返回[""].

返回:

  • 返回一個包含匹配項的 Array,每個匹配項對應一項。
  • 如果未找到匹配項,則返回 null

示例 1:使用 match()

const string = "I am learning JavaScript not Java.";
const re = /Java/;

let result = string.match(re);
console.log("Result of matching /Java/ :");
console.log(result);

const re1 = /Java/g;
let result1 = string.match(re1);

console.log("Result of matching /Java/ with g flag:")
console.log(result1);

輸出

Result of matching /Java/ :
[
  'Java',
  index: 14,
  input: 'I am learning JavaScript not Java.',
  groups: undefined
]
Result of matching /Java/ with g flag:
[ 'Java', 'Java' ]

在這裏,我們可以看到,如果不使用g 標誌,我們隻會得到第一個匹配結果,但包含索引、輸入和組等詳細信息。

注意: 如果正則表達式不包含g旗幟,str.match()將隻返回第一個匹配類似於RegExp.exec().返回的項目還將具有以下附加屬性:

  • groups - 命名捕獲組的對象,其鍵作為名稱,值作為捕獲的匹配項。
  • index - 找到結果的搜索索引。
  • input - 搜索字符串的副本。

示例 2:匹配字符串中的部分

const string = "My name is Albert. YOUR NAME is Soyuj.";

// expression matches case-insensitive "name is"+ any alphabets till period (.)
const re = /name\sis\s[a-zA-Z]+\./gi;

let result = string.match(re);
console.log(result); // [ 'name is Albert.', 'NAME is Soyuj.' ]

// using named capturing groups
const re1 = /name\sis\s(?<name>[a-zA-Z]+)\./i;
let found = string.match(re1);

console.log(found.groups); // {name: "Albert"}

輸出

[ 'name is Albert.', 'NAME is Soyuj.' ]
{name: "Albert"}

在這裏,我們使用了正則表達式來匹配字符串的某個部分。我們還可以使用如上所示的語法在匹配中捕獲某些組。

相關用法


注:本文由純淨天空篩選整理自 Javascript String match()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。