match() 方法,在字符串内找到相应的值并返回这些值,()内匹配字符串或者正则表达式。
该方法类似 indexOf() 和 lastIndexOf(),但是它返回指定的值,而不是字符串的位置。
<script type="text/javascript"> var str="1 plus 2 equal 3" document.write(`str.match(/\d+/g)`) </script>1demo1:<script type="text/javascript"> 2 3var str="Hello world!" 4document.write(str.match("world") + "<br />") 5document.write(str.match("World") + "<br />") 6document.write(str.match("worlld") + "<br />") 7document.write(str.match("world!")) 8 9</script> 10//结果 11world 12null 13null 14world! 15demo2:
输出:
11,2,3 2 3ps.引自http://www.w3school.com.cn/jsref/jsref_match.asp
通过已有的demo可以得出match()的适用环境,比如if判断中
1<!DOCTYPE html> 2<html> 3<body> 4<script> 5function changeImage() 6{ 7element=document.getElementById('myimage') 8if (element.src.match("bulbon")) 9 { 10 element.src="/i/eg_bulboff.gif"; 11 } 12else 13 { 14 element.src="/i/eg_bulbon.gif"; 15 } 16} 17</script> 18 19<img id="myimage" onclick="changeImage()" src="/i/eg_bulboff.gif"> 20 21<p>点击灯泡来点亮或熄灭这盏灯</p> 22 23</body> 24</html>