Why is my Javascript regex output inconsistent?

In the browser console, the output of the following function is the string alterante true and false. Any ideas?

    function checkSpecificLanguage (text_val) {
    // Force string type`enter code here`


        var regex = / ^ [\ u3000- \ u303F \ u3040- \ u309F \ u30A0- \ u30FF \ uFF00- \ uFFEF \ u4E00- \ u9FAF \ u2605- \ u2606 \ u2190- \ u2195u203B] + $ / ig; 

        console.log (text_val + "-" + regex.test (text_val));
        console.log (text_val + "-" + regex.test (text_val));
        console.log (text_val + "-" + regex.test (text_val));
        console.log (text_val + "-" + regex.test (text_val));
        console.log (text_val + "-" + regex.test (text_val));


      return regex.test (text_val);
    }

checkSpecificLanguage ("で し た γ‚³ ン γ‚΅ γƒΌ γƒˆ");


+3


source to share


2 answers


You are using the global flag ( g

).

According to MDN:



As with exec()

(or in combination with), test()

being called multiple times on the same instance of the global regex will go past the previous match.

You can get around this by installing lastIndex

.

+3


source


Due to the modifier g

you used with test

.

MDN :

test()

called multiple times in the same global regex instance will go past the previous match.



Use regex.lastIndex = 0

after every solution to this problem. Or remove the modifier /g

if you don't need to match multiple times.

function checkSpecificLanguage(text_val) {
        var regex =   /^[\u3000-\u303F\u3040-\u309F\u30A0-\u30FF\uFF00-\uFFEF\u4E00-\u9FAF\u2605-\u2606\u2190-\u2195u203B]+$/ig; 
        console.log( text_val+"-"+regex.test(text_val) );
        regex.lastIndex = 0
        console.log( text_val+"-"+regex.test(text_val) );
        regex.lastIndex = 0
        console.log( text_val+"-"+regex.test(text_val) );
        regex.lastIndex = 0
        console.log( text_val+"-"+regex.test(text_val) );
        regex.lastIndex = 0
        console.log( text_val+"-"+regex.test(text_val) );
      return  regex.test(text_val);
    }
checkSpecificLanguage("γ§γ—γŸγ‚³γƒ³γ‚΅γƒΌγƒˆ");
      

Run codeHide result


+1


source







All Articles