http://jsfiddle.net/bpt33/
var t = "";
var a = ["atom-required","atom-label","atom-data-type","atom-regex"];
var r = /atom\-(label|required|regex|data\-type|class|is\-valid|field\-value|error)/i;
function test(a, r){
for(var i = 0; i<a.length; i++){
t += a[i] + " => " + r.test(a[i]) + "<br/>";
}
}
test(a, r);
t += "<br/>";
a = ["atom-required","atom-label","atom-data-type","atom-regex"];
var r = /atom\-(label|required|regex|data\-type|class|is\-valid|field\-value|error)/gi;
test(a, r);
$("#results").get(0).innerHTML = t;
When g is not specified, it works correctly,
atom-required => true
atom-label => true
atom-data-type => true
atom-regex => true
When g is specified, it works alternatively
atom-required => true
atom-label => false
atom-data-type => true
atom-regex => false
The g flag indicates that the regular expression should be tested against all possible matches in a string.
Definition and Usage The "g" modifier specifies a global match. A global match finds all matches (compared to only the first).
The test() method executes a search for a match between a regular expression and a specified string. Returns true or false . JavaScript RegExp objects are stateful when they have the global or sticky flags set (e.g., /foo/g or /foo/y ). They store a lastIndex from the previous match.
A regular expression followed by an asterisk ( * ) matches zero or more occurrences of the regular expression. If there is any choice, the first matching string in a line is used.
Because with the g
modifier, the regexp becomes stateful, and resumes the next search at the index after the last match.
When no match is found, it resets itself.
You can observe the starting point by using the .lastIndex
property.
r.lastIndex; // 0 or some higher index
You can reset it manually by setting that property to 0
.
r.lastIndex = 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With