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

js character limit makes one Chinese character count as two characters

巴扎黑
巴扎黑Original
2017-09-13 09:38:101628browse

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">

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)
	}
})

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!

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