2

I wrote this function:

function validateName(name) {
    var re = /^[a-zA-Z\s]+$/gim;
    console.log("@@ name = ", name);
    console.log("typeof(re) = ", typeof(re));
    console.log("test returns = %s,re = ", re.test(name),re);
    console.log("test returns = %s,re = ", re.test(name),re);
    console.log("test returns = %s,re = ", re.test(name),re);
    return (re.test(name));
}

When I call it with name = "user fifteen" I get:

@@ name =  user fifteen
typeof(re) =  object
test returns = true,re =  /^[a-zA-Z\s]+$/gim
test returns = false,re =  /^[a-zA-Z\s]+$/gim
test returns = true,re =  /^[a-zA-Z\s]+$/gim

So as you can see, sometimes I get true and some false. I noticed that this happens because of a global match flag, but I cannot understand why. Does anyone have an idea?

Thank you in advance

Dakkaron
  • 5,930
  • 2
  • 36
  • 51
Elena Ep
  • 45
  • 2
  • 7
  • *As with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match.* Source mdn – nu11p01n73R Jun 25 '15 at 14:48

0 Answers0