简体   繁体   中英

how can I fix this regular expression function?

This is the first part of my code in a function:

var pattern = new RegExp(myTypedString,"gi");

The goal is to populate results as I type in a text field. Everytime an input event is triggered I loop through an array of strings and check if my typed string exists in my array of strings using this code:

return pattern.test(myArrayString);

but luckily I've realised that one of the results was wrong and it was only happening to this particular case: when I type "t" or "T" I don't have a match in "Trafalgar Square" (a string from myArrayString), so I did a few debugging in the console and when I check the variable pattern doing console.log(pattern) it outputs this string: /t/gi , which i think it's where my problem relies... (later on this)

when I tried to replicate the problem typing:

var pattern = new RegExp('t',"gi")

and:

pattern.test('Trafalgar Square')

which gives me true at a first try, BUT... if I type this again:

pattern.test('Trafalgar Square')

the result will be false and if I continue, true , false , true , false ,...

One of the first things that came into my mind is that the /t in the regex /t/gi might be a rule but I couldn't find anything about it.

I would like to know an explanation for this unexpected result but I'm also concerned that my function is not flawless, so I ask you how can I improve this function ? thanks

It alternates between true and false because it matches the first time ( true ), then tries a second match, which fails because there's only one T in Trafalgar Square . When you call it again, it loop back, thus the true , false , true , etc.

To fix that, update its cursor before matching:

var p = new Regexp('t', 'gi') // same as `p = /t/gi`

// ...
p.lastIndex = 0;
p.test("Trafalgar Square"); // true

// try again:
p.lastIndex = 0;
p.test("Trafalgar Square"); // true -> it works

Here is a relevant jsfiddle with a couple examples.

I do not know why it alternates between true and false (i can reproduce it, too). The /t/ should not be anything special in the regex. It is not a special character like { or \\ or [ and should just be a literal character t.

But you could use another function to achieve more or less the same:

'Trafalgar Square'.match(pattern)
=> Array [ "T" ]

'lalala'.match(pattern)
=> null

match takes slightly more resources than test would, but this is usually not a problem. The result will be an Array for matches or null when nothing matches, so you can just return that and the rest of your code will probably work just fine. Array... will be a truthy value and null will be a falsy value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM