JS controls the length of the string in the input box

  • 2020-03-30 03:01:19
  • OfStack


//Gets the length of the string in bytes
function len(s) {
s = String(s);
return s.length + (s.match(/[^x00-xff]/g) || "").length;//Plus the length of the full Angle character that matches
}
function limit(obj, limit) {
var val = obj.value;
if (len(val) > limit) {
val=val.substring(0,limit);
while (len(val) > limit){
val = val.substring(0, val.length - 1);
};
obj.value = val;
}
}
$("#nickName").keyup(function(){
limit(this,20);//Within 20 bytes
})


Related articles: