Skip to content
Advertisement

How to compare value in JavaScript when keyup

I try to compare two string first ASCII (English) and second Unicode (Chinese). User need to type message in textarea and JavaScript will calculate how long the text and show some message.

Now its working only for ASCII (English) but I need to compare because condition for ASCII and Unicode is different.

Below is my current code snippet:

JavaScript

For ASCII (English) I start with 152 but in Unicode (Chinese) I need to start with 60 and increase …

Below is the code that I’m using in PHP to check text/string in English or Chinese:

JavaScript

So my problem now I need to check the string is type in ASCII or Unicode then if Chinese start condition value with 60 or if English start with 152.

Check my jsfiddle here.

Advertisement

Answer

Taken from this Answer

The following regex [^x00-x80]+ can be used to test for non ASCII characters. ([^u0000-u0080]+ for non Unicode Chars)

I assumed you want to match against non ASCII characters, that wasn’t made clear in your question

Update: If you want to match only Chinese Characters use this instead

var isChinese = /[u4E00-u9FFFu6300-u77FFu7800-u8CFFu8D00-u9FFF]+/

Given this you can just test the RegExp against the Text and display the according Message

I slimmed the code a little for demo simplicities sake, it only accounts for steps of 60/152

JavaScript

Heres a Demo on JSFiddle

Update

So i changed it a little, to display an Error for non Chinese Unicode Characters. And let you define custom ranges

JavaScript

Heres another Fiddle for you

Advertisement