The title is too long. use javascript to intercept string by byte _ javascript skills

Source: Internet
Author: User
It is often encountered in Web display. The title is too long and the string needs to be intercepted. If CSS is used, there are various compatibility problems, the following describes how to intercept a string by byte in javascript as a front-end developer who often encounters this problem during webpage display. The title is too long and the string needs to be intercepted. If CSS is used for implementation, various compatibility problems will occur, various pitfalls.

Let the background program intercept a bit, and a variety of pushes, let the background cut by byte is the same as the old-fashioned background, and finally may only cut the length of the security characters for you, the last look is not good, not neat, still turn back to the CSS, debugging compatibility;

The front-end students who have the above feelings quietly likes it.

I recently came into contact with a project. The backend only provides interfaces (json). Data Rendering and data binding on all pages are handed over to the front-end. Finally, without thinking about SEO, all the initiative on the page is in the hands of even hands, inadvertently encountering the old problem of byte truncation.

Spread a Javascript code on the network to get the length of bytes:

The Code is as follows:


String. prototype. Blength = function () {// returns the length of String bytes.
Return this. replace (/([^ \ x00-\ xFF])/g, "aa"). length;
};


It is really easy. The characters larger than the ASCII code are counted as two bytes. Although strictly speaking, they are not correct, but we are used to help demonstrate the effect. It is really difficult to strictly enforce them,

But I always feel that it is not good to use regular expressions, which is a little opportunistic. In fact, it saves two lines of code, so I decided to use the normal calculation method:

The Code is as follows:


Function getBlength (str ){
For (var I = str. length; I --;){
N + = str. charCodeAt (I)> 255? 2: 1;
}
Return n;
}


I didn't extend the method to the prototype of the String object, or because of efficiency issues, the following is the test code:

The Code is as follows:


// Extended to the prototype of String
String. prototype. Blength = function (){
Var str = this,
N = 0;
For (var I = str. length; I --;){
N + = str. charCodeAt (I)> 255? 2: 1;
}
Return n;
}
// Add a method to the String object
String. getBlength = function (str ){
For (var I = str. length, n = 0; I --;){
N + = str. charCodeAt (I)> 255? 2: 1;
}
Return n;
}
// Construct a long string that combines Chinese and English
Var str = "javascript efficient byte string truncation method getBlengthjavascript efficient byte string truncation method getBlength ";
Str = str. replace (/./g, str). replace (/./g, str );
Console. log ("the length of the created string is:", str. length)
Console. log ("------------- test started --------------")
Console. log ("str. Blength ()>", str. Blength ())
Console. log ("String. getBlength (str)>", String. getBlength (str ))
Console. log ("-- efficiency test started --")

Var time1 = new Date ()
For (var I = 0; I <100; I ++ ){
Str. Blength ()
}
Console. log ("Blength time consumed:", new Date ()-time1 );

Var time2 = new Date ()
For (var I = 0; I <100; I ++ ){
String. getBlength (str)
}
Console. log ("getBlength time consumed:", new Date ()-time2 );


The efficiency of the results is not half past one. As for the reason, the time may be spent on the retrieval of the prototype chain. I did not go deep into it. If I know it, I can leave a message to tell me:

The length of the created string is 314432.
------------- Test start --------------

The Code is as follows:


Str. Blength ()> & gt; 425408
String. getBlength (str) >>> 425408
-- Efficiency test started --
Blength time consumption: 1774
GetBlength time consumption: 95


Now we have the basic function to intercept strings. In this case, the maximum length of the characters is 2. Therefore, it is better to use the binary method to find a proper position for intercept.

It should be a good truncation function to give:

The Code is as follows:


// Calculate the byte length
String. getBlength = function (str ){
For (var I = str. length, n = 0; I --;){
N + = str. charCodeAt (I)> 255? 2: 1;
}
Return n;
}
// Truncate a string in specified bytes
String. cutByte = function (str, len, endstr ){
Var len = + len
, Endstr = typeof (endstr) = 'undefined '? "...": Endstr. toString ();
Function n2 (a) {var n = a/2 | 0; return (n> 0? N: 1)} // used for Binary Lookup
If (! (Str + ""). length |! Len | len <= 0) {return "";}
If (this. getBlength (str) <= len) {return str;} // the most time-consuming judgment in the entire function. You are welcome to optimize it.
Var lenS = len-this. getBlength (endstr)
, _ LenS = 0
, _ Strl = 0
While (_ strl <= lenS ){
Var _ lenS1 = n2 (lenS-_ strl)
_ Strl + = this. getBlength (str. substr (_ lenS, _ lenS1 ))
_ LenS + = _ lenS1
}
Return str. substr (0, _ lenS-1) + endstr
}


Take the above string to test it. The longer the load is, the longer the load is, the more time it takes to cut the length of 20 W. Try:

The Code is as follows:


Console. log ("the length of the created String is:", str. length, "the byte length is:", String. getBlength (str ))
Console. log ("------------- test started --------------")
Console. log ("String. cutByte ('1 start 1', 6 ,'... ')> ", String. cutByte ('1 start 1', 6 ,'... '))
Console. log ("String. cutByte (str, 12, '...')>", String. cutByte (str, 12 ,'...'))
Console. log ("String. cutByte (str, 13, '..')>", String. cutByte (str, 13 ,'..'))
Console. log ("String. cutByte (str, 14, '.')>", String. cutByte (str, 14 ,'.'))
Console. log ("String. cutByte (str, 15,'')> ", String. cutByte (str, 15 ,''))
Console. log ("-- efficiency test started --")
Var time1 = new Date ()
For (var I = 0; I <100; I ++ ){
String. cutByte (str, 200000 ,'...')
}
Console. log ("Time consumed:", new Date ()-time1 );


Output result:

The length of the created string is 314432 bytes and 425408 bytes.
------------- Test start --------------

The Code is as follows:


String. cutByte ('1 start 1', 6, '...')> 1 start 1
String. cutByte (str, 12, '...')> expose crip...
String. cutByte (str, 13, '...')> javascript ..
String. cutByte (str, 14, '.')> javascript height.
String. cutByte (str, 15, '')> javascript height


-- Efficiency test started --
Duration: 155

In fact, changing the length of intercepted characters to 30 W and 40 W is not much time-consuming. In the face of the binary method, this is a level

Compare the time used to calculate the length of the byte, and use the binary search to extract the time that only consumes less than two bytes.

Finally, let's challenge the efficiency!
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.