关于IE的RegExp.exec的问题

代码如下:


代码如下:

var st="A[B]C[D]E[F]G";
var reg =/\[\w\]/ig;
var s1 = st.replace(reg,"");
var s2=[];
var arr;
while((arr=reg.exec(st))!=null)s2.push(arr[0]);
alert(s1);
alert(s2.join(""));

FF下正确显示,IE下S2为空.

网上查不到资料,请各位指点一二.

查询过程中得了个意外收获


代码如下:

var st="A[B]C[D]E[F]G";
var reg =/\[\w\]/ig;
var s1 = st.replace(reg,"");
var s2=[];

var arr;
while((arr=/\[\w\]/ig.exec(st))!=null)s2.push(arr[0]);
alert(s1);
alert(s2.join(""));

该写法IE死循环RegExp的lastIndex没有得到更新

In some recent code, I'm using Javascript to parse through the result set of an AJAX call, which happens to be returning a full HTML page. Yes, ideally, I'd have an AJAX call return something usable like JSON, but in this case the PHP back-end code had to remain as is and the front-end adjust to handle the legacy HTML it returned.
I needed to grab a link (1 or more) from the returned HTML page so that I could immediately display those links in separate windows (each was a generated report). So, my first stab at this is shown in the following code example. Basically, we have setup a string to represent the returned HTML, in this case it contains 3 <a> links; and we want to use the standard Javascript RegExp object's exec() method to grab the URLS (href parameter) for each of those links. In our example, we just print them out in an unordered list to see what we've captured. The important lines of code we'll be looking at are highlighted in the example below.


代码如下:

var s='<a href="x">X</a>\n<a href="y">Y</a>\n<a href="z">Z</a>\n';
document.write('Found the following link URLs in the string:<br/><ul>');
while (matches = /<a href=['"](.*)['"]>.*<\/a>/g.exec(s)) {
document.write('<li>' + matches[1] + '</li>\n');
}
document.write('</ul>');

Which, when run, we get the following results in Firefox/Safari/Chrome:
Found the following link URLs in the string:
x
y
z
Our while loop using RegExp.exec() on our in-line regular expression does what it's supposed to and continues to match from where it left off in the string giving us our captured portion in the matches[] array. However, when run in Internet Explorer, we get the following lovely result (at least up until IE tells us the script is no longer responding and asks us to kill it):
Found the following link URLs in the string:
x
x
x
x
x
x
x
x
x
…ad infinitum…
Obviously, we have generated an infinite loop using our code above in IE; but why? The issue is that IE doesn't correctly maintain the lastIndex member for the regular expression object each iteration through the loop. Each time through the loop, which if you look at the highlighted code is in-lined, IE creates a new RegExp object and hence resets the lastIndex member to the beginning of the string. Therefore, we match the first link in the string infinitely as the lastIndex pointer never progresses between matches. There is a way around this, and that is to declare the regular expression separately, outside the loop, (it gets created just once) and then call exec() on that singular RegExp object as follows:


代码如下:

var rx = /<a href=['"](.*)['"]>.*<\/a>/g;
var s='<a href="x">X</a>\n<a href="y">Y</a>\n<a href="z">Z</a>\n';
document.write('Found the following link URLs in the string:<br/><ul>');
while (matches = rx.exec(s)) {
document.write('<li>' + matches[1] + '</li>\n');
}
document.write('</ul>');

Now, the lastIndex member of our RegExp object gets updated correctly and we get the results we expected. Somewhat related to this item is the following interesting lastIndex bug in IE with zero-length matches. Hopefully, this will save someone a headache when trying to debug using Javascript RegExp.exec().

(0)

相关推荐

  • 关于IE的RegExp.exec的问题

    代码如下: 复制代码 代码如下: var st="A[B]C[D]E[F]G"; var reg =/\[\w\]/ig; var s1 = st.replace(reg,""); var s2=[]; var arr; while((arr=reg.exec(st))!=null)s2.push(arr[0]); alert(s1); alert(s2.join("")); FF下正确显示,IE下S2为空. 网上查不到资料,请各位指点一二. 查

  • javascript 中String.match()与RegExp.exec()的区别说明

    1. 这两个方法,如果匹配成功,返回一个数组,匹配失败,返回null. 2. 当RegExp的global属性为false时,这两个方法的返回数组是一样的. 数组的第0个元素是整个pattern的第一个匹配字符串,接下来的元素是pattern第一个匹配中的子匹配字符串. 此外,数组还有index和input两个额外属性,index是匹配字符串的起始位置,input是整个输入字符串. 此时,RegExp的lastIndex属性一直是0. demo: 复制代码 代码如下: var s = 'this

  • 浅谈JS正则表达式的RegExp对象和括号的使用

    RegExp对象的创建: 常规的正则表达式的创建可用直接量,即斜杠 "/" 括起来的字符.但在要求参数变化的环境下,RegExp()构造函数是更好的选择: var reg1 = /'\w+'/g; var reg2 = new RegExp('\'\\w+\'','g'); 对比两种创建方式,RegExp中的第一个参数为要创建的正则字符串,一方面注意,因为不是直接量的表示形式,因此不用斜杠" / "括起来了:而是字符串中必须要对引号" ' "和转

  • js正则表达式中test,exec,match方法的区别说明

    js正则表达式中test,exec,match方法的区别说明 test test 返回 Boolean,查找对应的字符串中是否存在模式.var str = "1a1b1c";var reg = new RegExp("1.", "");alert(reg.test(str)); // true exec exec 查找并返回当前的匹配结果,并以数组的形式返回.var str = "1a1b1c";var reg = new R

  • js的正则test,match,exec详细解析

    正则表达式gi我刚开始也看不懂,从网上找到后看到了,现在分享给大家正在表达式的通项: /pattern/flags 即(/模式/标记 ) 构造器函数方法使用方法如下:new RegExp("pattern"[, "flags"])即new RegExp("模式"[,"标记"])参数:pattern(模式)表示正则表达式的文本flags(标记)如果指定此项,flags可以是下面值之一:g: global match(全定匹配)i

  • JS正则中的match与exec使用说明

    主要参考W3C教程 String.match() match() 方法将检索目标字符串,以找到一个或多个与 正则表达式regexp 匹配的文本.match()有两种情况: <!--[if !supportLists]-->1. <!--[endif]-->如果 regexp 具有标志 g,则 match() 方法将执行全局检索,找到目标字符串中的所有匹配子字符串. 匹配情况 返回值 没有找到任何匹配的子串 null 找到了一个或多个匹配子串 一个数组.数组的内容包含所有的匹配子串

  • JavaScript RegExp 正则表达式对象详细说明

    直接量语法 /pattern/attributes 创建 RegExp 对象的语法: 复制代码 代码如下: var obj=new RegExp(pattern,attributes); 事例1: 复制代码 代码如下: var pattern=/a/; document.write(pattern.exec("asdas")); 事例2: 复制代码 代码如下: var obj=new RegExp("a"); document.write(obj.exec(&quo

  • javascript正则表达式和字符串RegExp and String(二)

    在上篇文章给大家介绍了javascript正则表达式和字符串RegExp and String(一),本文给大家继续分享相关内容. 前言 我认为,在学习一门编程语言的过程中,字符串.数组.容器是非常重要的部分,为了提高编程效率,我通常会对字符串.数组以及容器作深入的学习,详细了解相关特点及对应的API.这篇文章是针对javascript字符串学习写下的笔记,在此与需要的朋友分享. 思维导图 字符串的创建方式 字符串是javascript中的基本类型之一,它对应的类型是String,可以通过两种方

  • 在JavaScript的正则表达式中使用exec()方法

    exec方法为正则表达式匹配的文本搜索字符串.如果找到匹配,则返回结果数组; 否则,返回null. 语法 RegExpObject.exec( string ); 下面是参数的详细信息: string : 要搜索的字符串 返回值: 如果找到一个匹配,如果不为空,则返回匹配的文本. 例子: <html> <head> <title>JavaScript RegExp exec Method</title> </head> <body>

  • 每天一篇javascript学习小结(RegExp对象)

    1.正则表达式test方法 var text = "cat, bat, sat, fat"; var pattern = /.at/; if (pattern.test(text)){ alert("The pattern was matched."); } 2.正则的toString()方法 var pattern = new RegExp("\\[bc\\]at", "gi"); alert(pattern.toStrin

随机推荐