JavaScript正则表达式小结(test|match|search|replace|split|exec)
学JavaScript正则的好文一篇:http://www.cainiao8.com/web/js_note/js_regular_expression.html
test:测试string是否包含有匹配结果,包含返回true,不包含返回false。
<script type="text/javascript"> var str = "bbs.byr.cn"; var reg = /b/; var ret = reg.test(str); alert(ret); //true </script>
match:根据pattern进行正则匹配,如果匹配到,返回匹配结果,如匹配不到返回null
<script type="text/javascript"> var str = "ThIS isn't me"; var reg = /is/ig; var ret = str.match(reg); alert(ret); //IS, is console.log(ret); //["IS", "is"] </script>
search :根据pattern进行正则匹配,如果匹配到一个结果,则返回它的索引数;否则返回-1
<script type="text/javascript"> var str = "This isn't me"; var reg = /is/; var ret = str.search(reg); alert(ret);//2 </script>
replace:根据pattern进行正则匹配,把匹配结果替换为replacement
<script type="text/javascript"> var str = "i love china!"; var pattern = /i/g; var ret = str.replace(pattern, "I"); alert(ret); //I love chIna! </script>
split:根据pattern进行正则分割,返回一个分割的数组
<script type="text/javascript"> var str = 'http://www.baidu.com/'; var reg = /\W/; var ret = str.split(reg); console.log(ret); //["http", "", "", "www", "baidu", "com", ""] </script>
exec:对string进行正则处理,并返回匹配结果.array[0]为原字符串,array[i]为匹配在整个被搜索字符串中的位置。
<script type="text/javascript"> var str = "i love china!"; var reg = /i\B/g; var ret = reg.exec(str); alert(ret); // i console.log(ret); //["i", index: 9, input: "i love china!"] </script>
相关推荐
niuyongaiai 2013-06-09
shqhope 2020-06-23
满地星辰 2020-09-16
WebVincent 2020-06-16
lynjay 2020-06-14
ajaxtony 2020-06-11
有梦就能实现 2020-06-05
zhendeshifeng 2020-05-27
gcgl000hugang 2020-02-10
Yasin 2020-05-05
Darklovy 2020-04-16
hellobabygogo 2020-03-06
程松 2020-02-23
wbingyang 2020-02-16
文山羊 2020-02-14
zehuawong 2020-02-11
jiahaohappy 2020-01-10