Use pure JS Code to determine the number of Chinese characters in a string (super simple and practical). js is simple and practical.
In website development, JavaScript code is often used to determine the number of Chinese characters in a string. Today, I will take the time to share with you the implementation code. If you don't talk much about it, You can directly post code to everyone.
$ ("Form "). submit (function () {var content = editor. getContentTxt (); var sum = 0; re =/[\ u4E00-\ u9FA5]/g; // test the regular if (content) {if (re. test (content) // use regular expressions to determine whether a Chinese character exists. {if (content. match (re ). length <= 10) {// returns the number of Chinese characters $. dialog. tips ("the post body cannot contain less than 10 Chinese characters! "); Return false;} else {var $ submit = $ (" input [type = 'submit '] "). attr ("disabled", true); setTimeout (function () {$ submit. attr ("disabled", false) }, 5000); return true ;}} else {$. dialog. tips ("the post body cannot contain less than 10 Chinese characters! "); Return false ;}} else {$. dialog. tips (" the post body cannot contain less than 10 Chinese characters! "); Return false ;}});
Well, the above Code is the implementation method of js to determine the number of Chinese characters in a string.
Ps: JS determines the length of the input string (two Chinese characters, one letter or number)
The Chinese Character occupies 2 Characters in the database. If the input character exceeds the length of the field in the database table, an error occurs. Therefore, you must make a judgment on the foreground. There are two ways to judge:
Method 1: Use a regular expression. The Code is as follows:
function getByteLen(val) {var len = 0;for (var i = 0; i < val.length; i++) {var a = val.charAt(i);if (a.match(/[^\x00-\xff]/ig) != null) {len += 2;}else{len += 1;}}return len;}
Method 2: Use the unicode Character for determination: The method is as follows:
function getByteLen(val) {var len = 0;for (var i = 0; i < val.length; i++) {var length = val.charCodeAt(i);if(length>=0&&length<=128){len += 1;}else{len += 2;}}return len;}
The above section describes how to use pure JS Code to determine the number of Chinese characters in a string (super simple and practical). I hope it will be helpful to you, if you have any questions, please leave a message. The editor will reply to you in time.