How to find out if there is any UTF8 character in a string with Javascript?

I have a line like this: "Xin chào tảt cả mọi người". There are some Unicode characters in the string. All I want to do is write a function (in JS) to check if at least one Unicode character exists.

+3
source share
2 answers

A string is a sequence of characters, each of which has a character code. ASCII defines characters from 0 to 127, so if a character in a string has a code other than this, then it is a Unicode character. This function checks this. 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")

+2
source

function hasUnicode(s) {
    return /[^\u0000-\u007f]/.test(s);
}
0

All Articles