赞
踩
都能够测试字符串中是否存在指定格式的字符。两种方法主要的区别在于,调用方法的对象和传递的参数,正则表达式的方法调用方法的对象是正则表达式,传输的参数是字符串,而字符串的模式匹配调用方法的对象是字符串,传递的参数是正则表达式。
RegExp对象的方法:
例:
var text = "cat,bat,sat,fat";
var pattern = /.at/g;
console.log(pattern.exec(text));
//输出为:['cat',index:0,input:'cat,bat,sat,fat']
console.log(pattern.exec(text));
//输出为:['bat',index:4,input:'cat,bat,sat,fat']
例:
var text = "010-10086";
var pattern = /\d{3}-\d{5}/;
var flag = pattern.test(text);//true
String类型的模式匹配方法:
例:
var text = "cat,bat,sat,fat";
var pattern = /.at/g;
console.log(text.match(pattern));
//输出为:['cat','bat','sat','fat']
console.log(text.match(pattern));
//输出为:['cat','bat','sat','fat']
var text = "cat,bat,sat,fat";
console.log(text.search(/at/));//1
var text = "cat,bat,sat,fat";
console.log(text.replace(/at/g,"ond"));
//输出:cond,bond,sond,fond
var text = "cat,bat,sat,fat";
console.log(text.split(/[^\,]+/));
//输出:["",",",",",",",""]
console.log(text.split(/[^\,]+/),2);
//输出:["",","]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。