JS学习之路之JavaScript match() 方法


match() 方法,在字符串内找到相应的值并返回这些值,()内匹配字符串或者正则表达式。

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

demo1:

<
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!
demo2:
<script type="text/javascript">

var str="1 plus 2 equal 3"
document.write(str.match(/\d+/g))

</script>
 
 

输出:

 
 
1,2,3
ps.引自http://www.w3school.com.cn/jsref/jsref_match.asp

通过已有的demo可以得出match()的适用环境,比如if判断中

<!DOCTYPE html>
<html>
<body>
<script>
function changeImage()
{
element=document.getElementById('myimage')
if (element.src.match("bulbon"))
  {
  element.src="/i/eg_bulboff.gif";
  }
else
  {
  element.src="/i/eg_bulbon.gif";
  }
}
</script>

<img id="myimage" onclick="changeImage()" src="/i/eg_bulboff.gif">

<p>点击灯泡来点亮或熄灭这盏灯</p>

</body>
</html>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM