This article mainly introduces you to the implementation method of JS to determine how many Chinese characters are in a string, and then shares with you two methods of using JS to determine the length of the input string. It is very good and has reference value. Friends who are interested Let’s take a look
In website development, js code is often simply used to determine how many Chinese characters are in a string. Today I take the time to share with you the implementation code. Without further ado, I will just post the code for you.
$("form").submit(function () { var content = editor.getContentTxt(); var sum = 0; re = /[\u4E00-\u9FA5]/g; //测试中文字符的正则 if (content) { if (re.test(content)) //使用正则判断是否存在中文 { if (content.match(re).length <= 10) { //返回中文的个数 $.dialog.tips("帖子正文不能小于10个汉字!"); return false; } else { var $submit = $("input[type='submit']").attr("disabled", true); setTimeout(function () { $submit.attr("disabled", false) }, 5000); return true; } } else { $.dialog.tips("帖子正文不能小于10个汉字!"); return false; } } else { $.dialog.tips("帖子正文不能小于10个汉字!"); return false; } });
Okay, the above code is the implementation method of js to determine how many Chinese characters there are in a string.
ps: JS determines the length of the input string (Chinese characters count as two characters, alphanumeric characters count as one)
Chinese characters in the database occupies 2 characters. If the input characters exceed the length of the database table field, an error will occur, so judgment needs to be made at the front desk. There are two ways to judge:
Method 1: Use regular expressions, 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 character unicode to judge: 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 is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
How to use JavaScript to obtain barcodes based on images
Code for implementing the backgammon game using native JS Canvas
The above is the detailed content of How to determine how many Chinese characters there are in a string using pure JS code. For more information, please follow other related articles on the PHP Chinese website!