Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know there is any UTF8 character in a string with Javascript?

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.

like image 890
Nấm Lùn Avatar asked Feb 12 '14 04:02

Nấm Lùn


2 Answers

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")

like image 82
rvighne Avatar answered Sep 18 '22 23:09

rvighne


Here's a different approach using regular expressions

function hasUnicode(s) {
    return /[^\u0000-\u007f]/.test(s);
}
like image 36
HeberLZ Avatar answered Sep 17 '22 23:09

HeberLZ