Home > Web Front-end > JS Tutorial > js character limit makes one Chinese character count as two characters

js character limit makes one Chinese character count as two characters

巴扎黑
Release: 2017-09-13 09:38:10
Original
1688 people have browsed it

Sometimes we need to limit user input or intercept a string of a certain length, and we need to use such functional code. Here, the editor of Script House will share it with you

html


<input type="text" id="txt">
Copy after login

Core js code


//字符串截取
function getByteVal(val, max) {
	var returnValue = &#39;&#39;;
	var byteValLen = 0;
	for (var i = 0; i < val.length; i++) {
		if (val[i].match(/[^\x00-\xff]/ig) != null)
		byteValLen += 2;
		else
		byteValLen += 1;
		if (byteValLen > max)
		break;
		returnValue += val[i];
	}
	return returnValue;
}
$(&#39;#txt&#39;).bind(&#39;keyup&#39;,function(){
	var val=this.value;
	if(val.replace(/[^\x00-\xff]/g,"**").length>14){
		this.value=getByteVal(val,14)
	}
})
Copy after login

Note: jquery binding events are used in the code, so the jquery framework needs to be added.

The above is the detailed content of js character limit makes one Chinese character count as two characters. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template