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
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("γ§γγγ³γ³γ΅γΌγ");
+1
source to share