Home > Web Front-end > JS Tutorial > body text

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

WBOY
Release: 2016-05-16 16:43:25
Original
1087 people have browsed it

以下的代码,是测试从字符串中识别出年月日,可以看到创建的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);
Copy after login

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

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

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template