Home >Web Front-end >JS Tutorial >js character limit makes one Chinese character count as two characters
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 = ''; 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; } $('#txt').bind('keyup',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!