JavaScript正则表达式——函数

1.定义

方式一:
var  reg=new RegExp('abc','gi');  
//修饰符通常有三种,i,g,m,i表示忽略大小,g表示全局匹配即匹配到第一个之后不停止继续匹配,m表示多行匹配即遇到换行后不停止匹配继续直到被匹配字符串结束。
方式二: var reg=/abc/gi;

2.正则对象的方法,regObj.test,regObj.exec及regObj.compile。

test(),测试某个字符串是否与正则匹配
var reg = /boy(s)?s+ands+girl(s)?/gi;
var str = "boy and girl";
reg.test(str);
//true
exce(),匹配文本并返回结果数组,否则返回null。
compile(),方法用于在脚本执行过程中编译正则表达式。
var str="Every man in the world! Every woman on earth!";
patt=/(wo)?man/g;
patt.compile(patt);
str2=str.replace(patt,"person");
console.log(str2);
"Every person in the world! Every person on earth!"

3.String对象的方法

search(regexp/substr),查找第一次匹配的子字符串的位置,没有返回-1。
var str = "hello world";
str.search(/o/g);
//4
var str = "hello world";
str.search(/i/g);
//-1
replace(regexp/substr,replacement),替换。
var str="hello world!";
console.log(str.replace(/hello/g,'hi'));
hi world!
split(separator,howmany),separator必需,子字符串或正则表达式,howmany非必需,可指定返回的数组长度。
var str="How are you doing today?"
console.log(str.split(" ",3));
//["How", "are", "you"]
match(searchvalue/regexp),检索指定的值。
var str = "hello world,hi world!";
str.match(/world/g);
//["world", "world"]
var str = "hello world,hi world!";
str.match(/world/);
//["world"]
原文地址:https://www.cnblogs.com/lixuemin/p/5865870.html