除了RegExp中的test()和exec()方法,String对象也提供了4个使用正则表达式的方法。
1、match(pattern)
match(pattern)返回pattern中的子串或null,返回数组,数组中含有匹配的字符串。
示例代码:
var reg=/hello/;
var str="hello world,hello match";
alert(str.match(reg));//默认返回第一个字符串
效果图:
2、search(pattern)
search(pattern)返回字符串中pattern开始的位置
示例代码:
var reg=/hello/g;
var str="hello world,hello match";
alert(str.search(reg));//返回的是第一个位置
效果图:
3、replace(pattern,replacement)
replace(pattern,replacement) 用replacement 替换pattern
var reg=/hello/g;
var str="hello world,hello match";
alert(str.replace(reg,"replace"));
效果图:
4、split(pattern)
split(pattern) 返回字符串按指定 pattern 拆分的数组
示例代码:
var reg=/hello/g;
var str="hello world,hello test";
alert(str.split(reg));
效果图:
个人微信公众号:
如果我的文章对您有帮助,微信支付宝打赏: