I have a string such like that : "Xin chào tất cả mọi người". There are some Unicode characters in the string. All that I want is writing a function (in JS) to check if there is at least 1 Unicode character exists.
A string is a series of characters, each which have a character code. ASCII defines characters from 0 to 127, so if a character in the string has a code greater than that, then it is a Unicode character. This function checks for that. See String#charCodeAt.
function hasUnicode (str) {
for (var i = 0; i < str.length; i++) {
if (str.charCodeAt(i) > 127) return true;
}
return false;
}
Then use it like, hasUnicode("Xin chào tất cả mọi người")
Here's a different approach using regular expressions
function hasUnicode(s) {
return /[^\u0000-\u007f]/.test(s);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With