3

In browser console the output of the following function is a series of alterante true and false. Any idea?


    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("でしたコンサート");


paraS elixiR
  • 1,190
  • 1
  • 12
  • 22

2 Answers2

3

You're using a global (g) flag.

According to MDN:

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.

You can get around this by setting lastIndex.

Jack
  • 8,836
  • 2
  • 29
  • 44
1

Because of the g modifier that you used with test.

MDN:

test() called multiple times on the same global regular expression instance will advance past the previous match.

Use regex.lastIndex = 0 after each to solve this issue. Or remove the /g modifier if you do not 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("でしたコンサート");
Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476