Home  >  Article  >  Web Front-end  >  How to use pure JS code to determine how many Chinese characters there are in a string

How to use pure JS code to determine how many Chinese characters there are in a string

高洛峰
高洛峰Original
2016-12-07 10:07:361294browse

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=&#39;submit&#39;]").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 occupy 2 characters in the database. If the input characters exceed the length of the database table field, an error will occur, so it needs to be in the foreground Make judgments. 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;
}


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn