Same JavaScript function returns random results -
i'm confused:
function is_valid(name) { var regexp_name = /^(\d|\w)*$/gi; return regexp_name.test(name); } // console console.log(is_valid("test")); => true console.log(is_valid("test")); => false console.log(is_valid("test")); => true console.log(is_valid("test")); => false what doing wrong?
remove /g flag.
the regexp object somehow reused. when /g flag present, regex engine start previous matched location until whole string consumed.
1st call: test ^ after 1st call: test (found "test") ^ 2nd call: test ^ after 2nd call test (found nothing, reset) ^ btw, \w equivalent [0-9a-za-z_] in javascript. therefore, \d| , /i flag redundant. , since you're not using captured group, there's no need keep (…). following enough:
var regexp_name = /^\w*$/;
Comments
Post a Comment