0

On a website, a user enters some text in a search box, for example the letter "o".

This creates the following regular expression in the site's javascript code:

var filterSubstring = $("#FilterOnSubstringBox").val();
var regexp = new RegExp(filterSubstring,"gi");

Later on I loop over some strings, and test them against the regexp. I want to the testing to be case insenstive, so both "o" and "O" should match:

for(var i = 0; i < array.length; i++)
{
    var textToSearch = array[i].name;

    if(!regexp.test(textToSearch))
    {
        alert("NOT OK: " + textToSearch + " DID NOT CONTAIN: " + filterSubstring);  
    }
    else
    {
        alert("OK! " + textToSearch + " CONTAINS: " + filterSubstring);
    }
}

Unfortunately, I get the following weird results. I made a jsfiddle (http://jsfiddle.net/grs9xpek/) to show this.

When filtering on the letter 'o':

OK!: ontwerpbesluitenbundel.dmt CONTAINS: o
OK!: ontwerpbesluitenbundel_body.xta CONTAINS: o
NOT OK: ScriptTemplate.docx DID NOT CONTAIN: o
OK!: ShippingOrder.xta CONTAINS: o
NOT OK: header.xta DID NOT CONTAIN: o

-> scriptTemplate.docx is wrong.

when filtering on the word 'ont'

OK!: ontwerpbesluitenbundel.dmt CONTAINS: ont
NOT OK: ontwerpbesluitenbundel_body.xta DID NOT CONTAIN: ont
NOT OK: ScriptTemplate.docx DID NOT CONTAIN: ont
NOT OK: ShippingOrder.xta CONTAINS: ont
NOT OK: header.xta DID NOT CONTAIN: ont

-> ontwerpbesluitenbundel_body.xta is wrong.

Why are those names failing the regexp?

user1884155
  • 3,616
  • 4
  • 55
  • 108

1 Answers1

5

In global mode the test method starts at lastIndex, wich is updated and not reset, even when you use a different string. Resetting it manually to 0 should correct the problem :

    ...
    regexp.lastIndex = 0
    if(!regexp.test(textToSearch))
    ...
bwt
  • 17,292
  • 1
  • 42
  • 60
  • Could you give me a manual or reference that details this behaviour? Google is not my friend on finding a source for this. Thanks – user1884155 Oct 29 '14 at 13:55
  • It is detailed in sections 15.10.6.2 and 15.10.6.3 of the ECMAScript specifications (http://www.ecma-international.org/ecma-262/5.1/#sec-15.10.6.2) By the way I didn't know it only applies to global mode. I added this to the answer. – bwt Oct 30 '14 at 10:58
  • What does "global" mean in this context? On my jsFiddle, why is regexp global or not global and can you give an example of where it is (or isn't)? – user1884155 Oct 30 '14 at 14:01