Why output of my Javascript regex is inconsistent?
This question already has an answer here:
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
.
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-u303Fu3040-u309Fu30A0-u30FFuFF00-uFFEFu4E00-u9FAFu2605-u2606u2190-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("でしたコンサート");
链接地址: http://www.djcxy.com/p/92592.html
上一篇: 样式电子邮件地址验证