If you create a regular expression and set its global flag to true, it is important to note that if you want to test multiple strings against that RegExp using the test()
function you will most-likely want to zero out the regular expression’s lastIndex
property. Take the following code for example:
var word, words = "Hello world!".split(" "), regExpO = /o/g, i = 0;
while(word = words[i++]) {
console.log('"' + word + '" ' + (regExpO.test(word) ? 'passes' : 'fails'));
}
The following is output:
"Hello" passes
"world!" fails
On the other hand, if I were to zero out the lastIndex
property every time, both parts would pass:
var word, words = "Hello world!".split(" "), regExpO = /o/g, i = 0;
while(word = words[i++]) {
console.log('"' + word + '" ' + (regExpO.test(word) ? 'passes' : 'fails'));
regExpO.lastIndex = 0; // reset for next use of the text() function.
}
Now the following will be output:
"Hello" passes
"world!" passes
Although JavaScript is fun, at times it can be annoying as well because it at times acts different than you may expect. 8)
2 Comments
ildar · February 14, 2013 at 4:12 PM
Hi Chris,
You shouldn’t use global regexps in this manner because lastIndex property refers to the last index of the found pattern within the input string. So what do you do? You change the input string and try to apply the same regexp to another string. It is not good idea because you change the context of the applied regexp. So you have to use the particular regexp to the particular string from the very beginning until the very end of the string without changing of the input string.
Consider the situation. You read a chapter in the book. When the chapter is over you took another book and began reading it from the same page. If the second book is big enough you continue reading until the end of the current chapter. if the book is smaller than the previous one you can just observe the cover of the book because there is no the same page as in the previous book.
Chris West · February 15, 2013 at 1:12 AM
I understand that I could simply use a RegExp expression every time to avoid needing to define a constant and then reset its
lastIndex
property. The reason that I can’t in my current situation is because it is encouraged for us to define regular expressions that are often used as constants. This prevents the redefinition of the same RegExp over and over again. I guess the real question is, is it more advantageous to use the same RegExp multiple times and reset itslastIndex
than it is to define the same RegExp multiple times?