Unexpected JavaScript behavior error

I wrote this verification method, but I have problems with it.

function validate_password(pwd)
{
    var score = 0;

    // Min length is 8
    if (pwd.length<8)
        return false;

    // Is lower present?
    if (/[a-z]/g.test(pwd))
    {
        console.log('a-z test on "'+pwd+'":' + /[a-z]+/g.test(pwd));
        score++;
    }

    // Is upper present?
    if (/[A-Z]/g.test(pwd))
    {
        console.log('A-Z test on: "'+pwd+'":' + /[A-Z]+/g.test(pwd));
        score++;
    }

    // Is digit present?
    if (/\d/g.test(pwd))
    {
        console.log('digit test on: "'+pwd+'":' + /\d/g.test(pwd));
        score++;
    }

    // Is special char present?
    if (/\W/g.test(pwd))
    {
        console.log('spec char test on: "'+pwd+'":' + /\W/g.test(pwd));
        score++;
    }

    if (score>=3)
        return true;
    else
        return false;
}

This is what is written on the console:

>>> validate_password('aaasdfF#3s')
a-z test on "aaasdfF#3s":true
A-Z test on: "aaasdfF#3s":true
digit test on: "aaasdfF#3s":true
spec char test on: "aaasdfF#3s":true
true

>>> validate_password('aaasdfF#3s')
a-z test on "aaasdfF#3s":true
false

On the first try, it seems to work as expected, but when I call this method a second time, it does not work as expected.

So my question is: why are there differences between the results of the first attempt and the second attempt?

Thank!:)

+1
source share
1 answer

See the MDC documentation test.

, , ( String.search); ( ) exec ( String.match). exec, , , .

g :

/[a-z]/ /[a-z]/g ..

, , :

var l = /[a-z]/g;

// initial search starts at the beginning, matches "a" and returns true
l.test("a"); // true
// since the first character matched, lastIndex moves to the next index - 1
l.lastIndex; // 1

// this time we pass a different string to the regex, but unfortunatly it
// starts searching from the lastIndex which is 1. There are no lower case
// letters from this point onwards (only "---"), so return value is false.
l.test("x---"); // false
// Since this search failed, lastIndex wraps around to the beginning, so the 
// next search will work as expected
l.lastIndex; // 0

"aaasdfF#3s" [a-z] 7 , 7 , 8 . 9- 15- . , - "F", "#" "3", lastIndex 0, .

, -, , RegExp , RegExp , , . test :

function RegExpStatePersistenceTest() {
    var regex = /[a-z]/g;

    regex.counter = regex.counter || 0;
    regex.counter++;

    console.log("counter:" + regex.counter);
}

RegExpStatePersistenceTest(); // counter: 1
RegExpStatePersistenceTest(); // counter: 2
RegExpStatePersistenceTest(); // counter: 3
RegExpStatePersistenceTest();​ // counter: 4

new RegExp(..), RegExp, .

. why-regexp-with-global-flag-in-javascript-give-wrong-results

+1

Source: https://habr.com/ru/post/1756439/


All Articles