JS match() 方法
<html>
<body>
<script type="text/javascript">
var str="Hello world!"
document.write(str.match("world") + "<br />")
document.write(str.match("World") + "<br />")
document.write(str.match("worlld") + "<br />")
document.write(str.match("world!"))
</script>
</body>
</html>
-----------------------------------------------
结果为何是这样!
world
null
null
world!
js中match函数方法是使用正则表达式模式对字符串执行查找,并将包含查找的结果作为数组返回。使用方法:
stringObj.match(rgExp)
其中stringObj是必选项。对其进行查找的 String 对象或字符串文字。
rgExp是必选项。为包含正则表达式模式和可用标志的正则表达式对象。也可以是包含正则表达式模式和可用标志的变量名或字符串文字。
如果js中match函数方法没有找到匹配,返回 null。如果找到匹配返回一个数组并且更新全局 RegExp 对象的属性以反映匹配结果。JavaScript中match函数方法返回的数组有三薯衡个属性:input、index和lastIndex。Input 属性包含整个的被查找字符串。Index 属性包含了在整个被查找字符串中匹配的子字符串的位置。LastIndex 属性包含了最后一次匹缺纤配中最后一个字符的下一个位置。如果没有设置全局标志 (g),数组的0元素包含整个匹配,而第 1 到 n 元素包含了匹配中曾出现过的任一个子匹配。这相当于没有设置全局标志的 exec 方法。如果设置了全局标志,元素0到n中包含所有匹配。
下面的示例演示了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"
// 出现的四个匹配。
}
下面几行代码演示了字符串文字的js中match函数方法的用法。
var r, re = "Spain";
r = "The rain in Spain".replace(re, "Canada");
match()方法用于从字符串中查找指定的值,本方法类似于indexOf()和lastindexOf(),不同的是它返回的是指定的值,而不是指定值在字符串中的位置。indexOf()和lastindexOf()方法返回位置数字 如果找不到返回-1。注意区分大小写
<script type="text/javascript">
var str="Hello world!"
document.write(str.match("world") + ""数扮做)
document.write(str.match("World") + "")
document.write(str.match("worlld") + "")
document.write(str.match("world!"))
</script>
match() 方法可在字符串笑档内检索指定的值,或找到一个或多个正则表达式的匹配。
该方法类似 indexOf() 和 lastIndexOf(),但是它返回指定的值,而不是字符串的位置。
语法:
stringObject.match(searchvalue)
stringObject.match(regexp)
参数描述:
searchvalue 必需。团升扰规定要塌旦检索的字符串值。
regexp 必需。规定要匹配的模式的 RegExp 对象。如果该参数不是 RegExp 对象,则需要首先把它传递给 RegExp 构造函数,将其转换为 RegExp 对象。
例子:
<script type="text/javascript">
var str="Hello world!"
document.write(str.match("world") + "<br />")
document.write(str.match("World") + "<br />")
document.write(str.match("worlld") + "<br />")
document.write(str.match("world!"))
</script>
输出:
world
null
null
world!