user1884155
user1884155

Reputation: 3736

Javascript RegExp failing on simple input

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?

Upvotes: 0

Views: 63

Answers (1)

Philippe Banwarth
Philippe Banwarth

Reputation: 17725

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))
    ...

Upvotes: 5

Related Questions