javascript正则表达式

来源:互联网 发布:ubuntu 测试软件 编辑:程序博客网 时间:2024/06/09 22:06

RegExp可以是直接量也可以是对象

创建一个直接量

var re = /regular expression/;注意这个模式不是一个字符串

var re = /Shellys+Powers/i;

创建一个对象

var re = new RegExp("Shellys+Powers","i");

下面列出改对象的属性和方法:

1.RegExp test;匹配返回true, pattern.test("testString","i");

2.string match;testString.match(pattern);与test差不多,只不过用法不同,一个是string的方法,一个是RegExp的;

3.RegExp exec;执行正则表达式,匹配不成功返回null,否则返回带有信息的一个数组,返回的数组包含的是:

  实际匹配的值,在字符串中找到的索引,任何带圆括号的子字符串的匹配,以及最初的字符串。

4.正则replace;var re = /tw{2}e/g ;var replace = searchString.replace(re,"place");

 关于RegExp exec的用法:    

var searchString = "Now is the time for us and is not time for them the";var pattern = /tw*e/g;var matchArray;var str = "";matchArray = pattern.exec(searchString); while((matchArray = pattern.exec(searchString))!= null){      str = str + "at "+matchArray.index +" we found "+matchArray[0]+" ";      console.log(matchArray);}document.getElementById("test").innerHTML = str; 


0 0