当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Javascript match()用法及代码示例

string.match()是JavaScript中的内置函数,用于在字符串中搜索与任何正则表达式的匹配项,如果找到匹配项,则将匹配项作为数组返回。句法:

string.match(regExp)

参数:这里的参数是“regExp”,即正则表达式,它将与给定的字符串进行比较。
返回值:它将返回一个包含匹配项的数组,每个匹配项都包含一项;如果找不到匹配项,则返回Null。
JavaScript代码,显示match()函数的工作方式:
范例1:

Input: 
var string = Welcome to geeks for geeks!
document.write(string.match(/eek/g);
Output:
eek, eek

在上面的示例中,子字符串“eek”将与给定的字符串匹配,当找到匹配项时,它将返回一个字符串对象数组。此处“g”标志指示应针对字符串中所有可能的匹配项测试正则表达式。
代码1:


<script> 
  
    // initializing function to demonstrate match() 
    // method with "g" para 
    function matchString() { 
        var string = "Welcome to geeks for geeks"; 
        var result = string.match(/eek/g); 
        document.write("Output:" + result); 
    } matchString(); 
      
</script>                    

输出:

eek,eek

范例2:

Input:
var string = "Welcome to GEEKS for geeks!";
document.write(string.match(/eek/i);
Output:
EEK

在上面的示例中,子字符串“eek”将与给定的字符串匹配,如果找到匹配的字符串,它将立即返回。 “i”参数有助于在给定的字符串中找到区分大小写的匹配项。
代码2:

<script> 
  
    // initializing function to demonstrate match() 
    // method with "i" para 
    function matchString() { 
        var string = "Welcome to GEEKS for geeks!"; 
        var result = string.match(/eek/i); 
        document.write("Output:" + result); 
    } matchString(); 
      
</script>                    

输出:

EEK

范例3:

Input:
var string = "Welcome to GEEKS for geeks!";
document.write(string.match(/eek/gi);
Output:
EEK, eek

在上面的示例中,子字符串“eek”将与给定的字符串匹配,如果找到匹配的字符串,它将立即返回。 “gi”参数可帮助查找区分大小写的匹配以及给定字符串中的所有可能组合。
代码3:

<script> 
  
    // initializing function to demonstrate match() 
    // method with "gi" para 
    function matchString() { 
        var string = "Welcome to GEEKS for geeks!"; 
        var result = string.match(/eek/gi); 
        document.write("Output:" + result); 
    } matchString(); 
      
</script>                    

输出:

EEK,eek



注:本文由纯净天空筛选整理自kundankumarjha大神的英文原创作品 JavaScript | match()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。