当前位置:编程学习 > JS >>

javascript 查找字符串中特定的字符 match

定义和用法
match() 方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。

该方法类似 indexof() 和 lastindexof(),但是它返回指定的值,而不是字符串的位置。

语法
stringobject.match(searchvalue)
stringobject.match(regexp)

<script type="text/网页特效">
var str="hello world!"
document.write(str.match("world") + "<br />") //world
document.write(str.match("world") + "<br />") //null
document.write(str.match("worlld") + "<br />") //null
document.write(str.match("world!")) //world!
</script>


下面的示例演示了js中match函数方法的用法:

function matchdemo(){
   var r, re;         // 声明变量。
   var s = "the rain in spain falls mainly in the plain";
   re = /ain/i;    // 创建正则表达式模式。
   r = s.match(re);   // 尝试匹配搜索字符串。
   return(r);         // 返回第一次出现 "ain" 的地方。
}

本示例说明带 g 标志设置的js中match函数方法的用法

function matchdemo(){
   var r, re;         // 声明变量。
   var s = "the rain in spain falls mainly in the plain";
   re = /ain/ig;      // 创建正则表达式模式。
   r = s.match(re);   // 尝试去匹配搜索字符串。
   return(r);         // 返回的数组包含了所有 "ain"
                      // 出现的四个匹配。
}


注意:在全局检索模式下,match() 即不提供与子表达式匹配的文本的信息,也不声明每个匹配子串的位置。如果您需要这些全局检索的信息,可以使用 regexp.exec()。

补充:网页制作,js教程 
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,