Home  >  Article  >  Web Front-end  >  JavaScript-RegExp object can only be used once problem solution_javascript tips

JavaScript-RegExp object can only be used once problem solution_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:43:251091browse

以下的代码,是测试从字符串中识别出年月日,可以看到创建的rYMD这个RegExp对象执行了一次后,又执行了一次。

var DateStr = "2014-9-8"; 
var rYMD = new RegExp("(\\d{4}|\\d{2})-(\\d{2}|\\d{1})-(\\d{2}|\\d{1})", "g"); 
var aRt = rYMD.exec(DateStr); 
var sRt=rYMD.exec(DateStr);

经过调试,发现第一次执行,aRt得到了返回的Array(数组),但是紧跟其后的sRt却是null

经过反复尝试,发现是因为RegExp对象执行了一次后就废掉了。

所以,需要注意了,每次用RegExp都需要重新new一个。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn