Home  >  Article  >  Web Front-end  >  A simple example of js intercepting fixed-length Chinese and English characters_javascript skills

A simple example of js intercepting fixed-length Chinese and English characters_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:13:161261browse

Although js provides a function for calculating the number of bytes occupied by a string, it cannot correctly calculate the number of bytes occupied by Chinese characters, such as document.form1.username.value="I am Chinese",document.form1.username. value.length returns 5 instead of 10, which brings some troubles to programming, such as limiting the input of fixed-length characters and intercepting fixed-length strings. Because of this problem, the expected effect cannot be achieved. The following is what I wrote. A simple function, used to intercept fixed-length strings, applicable to both Chinese and English. If there is anything wrong, please correct me!

Copy code The code is as follows:

//js intercepts strings, both Chinese and English can be used
//If the given string is greater than the specified length, intercept the specified length and return it, otherwise return the source string.
function cutstr(str,len)
{
var str_length = 0;
var str_len = 0;
str_cut = new String();
str_len = str.length;
for(var i = 0;i {
a = str.charAt(i);
str_length ;
if(escape(a).length > 4 )
{
//The length of Chinese characters after encoding is greater than 4
str_length ;
}
str_cut = str_cut.concat(a);
if(str_length&g t;=len)
                                                                                                                                                                                                                                             Source string;
if(str_length return str;
}
}

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