The example in this article describes how JS determines the number of bytes in a string and intercepts the length. Share it with everyone for your reference, the details are as follows:
This is something I accumulated during the project production. I think the effect is okay. Now I’ll paste the effect:
So, on the page, we need to detect two things, one is the number of bytes and the other is the number of characters.
Since the database requires the length of title to be 200 bytes, the specific js code is as follows:
/************************************************************************* * CodeBy:SCY CodeDate:2011年3月11日 12:01:16 * DESC:主要是用来判断当前输入的字节数,以便做到限制输入标题的长度功能 **************************************************************************/ var matchWords; function notifyTextLength() { var inputNum = document.getElementById("txtTitle").value.replace(/[^\x00-\xff]/g, "**").length; //得到输入的字节数 if (inputNum <= 200) { matchWords = document.getElementById("txtTitle").value.length; document.getElementById("inputedWord").innerHTML = inputNum + "字节," + matchWords + "字符"; document.getElementById("inputtingWord").innerHTML = (200 - inputNum) + "字母,"+(Math.round(((200-inputNum)/2)-0.5))+"汉字"; } if (inputNum > 200) { document.getElementById("txtTitle").value = document.getElementById("txtTitle").value.substring(0, matchWords); //如果超过200字节,就截取到200字节 } }
Among them, matchWords represents the number of matching characters when the number of bytes is less than 200; inputNum is the number of input bytes.
When the number of bytes entered in the title is greater than 200, it will be intercepted according to the number of characters.
The html code is as follows:
<input id="txtTitle" type="text" class="inputText" runat="server" onpropertychange="notifyTextLength();" /> 当前已经输入<span id="inputedWord" style="color:red"></span> 还可以输入<span id="inputtingWord" style="color:Red;"></span>
Readers who are interested in more JavaScript-related content can check out the special topics on this site: "Summary of JavaScript search algorithm techniques", "Summary of JavaScript animation special effects and techniques", "Summary of JavaScript errors and debugging techniques", "Summary of JavaScript data structures and algorithm techniques", "Summary of JavaScript traversal algorithms and techniques" and "JavaScript Mathematics Summary of operation usage》
I hope this article will be helpful to everyone in JavaScript programming.