JavaScript 正则表达式(RegExp)

时光怂恿深爱的人放手 提交于 2020-03-03 07:50:11

什么是RegExp

RegExp是一种模式用来描述要检索的内容。

定义RegExp

1 var patt = new RegExp("模式");

RegExp对象的方法

RegExp对象有3个方法:test()、exec()、compile()

test()

检索字符串中指定的值。返回值为true或者false

1 var patt = new RegExp("e");
2 document.write(patt.test("I am a student");
3 //返回值
4 true

 

exec()

检索字符串中指定的值。返回值为找到的值,如果没有发现匹配,返回null。

1 var patt = new RegExp("e");
2 document.write(patt.exec("I am a student.);
3 //返回值
4 e

可以设定第二个参数来设定检索

g:全局检索

i:执行对大小写不敏感的匹配

m:执行多行匹配

1 var patt = new RegExp("e", "g");
2 do {
3     result = patt.exec("I am a student in the university");
4     document.write(result);
5 } while (result != null);
6 //执行结果
7 eeenull

compile()

用于改变RegExp。

即可以改变检索模式,也可以添加或删除第二个参数。

1 var patt = new RegExp("e");
2 document.write(patt.test("I am a student");
3 patt.compile("b");
4 document.write(patt.test("I am a student");
5 //输出结果
6 truefalse

 

 

 总结自:http://www.w3school.com.cn/js/js_obj_regexp.asp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!