Home > Web Front-end > JS Tutorial > If the title is too long, use javascript to intercept the string by bytes_javascript tips

If the title is too long, use javascript to intercept the string by bytes_javascript tips

WBOY
Release: 2016-05-16 16:51:22
Original
1305 people have browsed it

As a front-end developer, I often encounter in web page display that the title is too long and strings need to be intercepted. If implemented using CSS, there are various compatibility issues and various pitfalls.

Asking the background program to cut it, and making various excuses to ask the background to cut it by bytes is the same as killing the background. In the end, it may only be cut according to the character length, and the final result will not look good. If it’s not correct, it’s better to go back and adjust the CSS and adjust the compatibility;

Front-end students who have the above impressions can silently like it.

I recently came across a project where the backend only provided an interface (json), and the data rendering and data binding of all pages were left to the front end. Finally, regardless of SEO, all the initiative on the page was in my hands, and I inadvertently encountered the old problem of byte interception.

There is a Javascript method to simply obtain the byte length circulating on the Internet:

Copy code The code is as follows:

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

It’s really simple. Characters larger than the ASCII code are counted as two bytes. Although strictly speaking it’s not correct, we use it to assist the display effect. It’s not good if it’s really strict.

But I always feel that it’s just a little opportunistic, and it’s not good to use regular expressions, which are time-consuming. In fact, it only saves two lines of code, so I decided to use the normal method. Calculation:
Copy code The code is as follows:

function getBlength(str){
for (var i=str.length;i--;){
n = str.charCodeAt(i) > 255 ? 2 : 1;
}
return n;
}

I did not extend the method to the prototype of the String object, or because of efficiency issues, the following is the test code:
Copy code The code is as follows:

//Expand 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 mixed Chinese and English string first
var str = "javascript efficient interception of strings by bytes method getBlengthjavascript efficient interception of strings by bytes method getBlength";
str = str.replace(/./g, str).replace(/./g , str);
console.log("The length of the created string is: ",str.length)
console.log("-------------Test begins-- ------------")
console.log("str.Blength() >> ",str.Blength())
console.log("String.getBlength (str) >> ",String.getBlength(str))
console.log("--Efficiency test starts--")

var time1 = new Date()
for (var i=0;i<100;i ){
str.Blength()
}
console.log("Blength takes time: ",new Date() - time1);

var time2 = new Date()
for(var i=0;i<100;i ){
String.getBlength(str)
}
console.log("getBlength consumes When: ",new Date() - time2);

The result is not a little bit inefficient. As for the reason, it may be that time is spent on retrieving the prototype chain. I have not gone into it. I know it. Leave a message and tell me:

The length of the created string is: 314432
-------------Test begins-------------
Copy code The code is as follows:

str.Blength() >> 425408
String.getBlength(str) >> 425408
--Efficiency test starts--
Blength takes time: 1774
getBlength takes time: 95

Now to intercept The basic function of string is now available, because in this case the maximum length of bytes occupied by a character is 2, so it is best to use the binary method to find the appropriate interception position.

Give me an interception function that should be quite efficient:
Copy the code The code is as follows:

//Simple calculation of byte length
String.getBlength = function (str) {
for (var i = str.length, n = 0; i--; ) {
n = str.charCodeAt(i) > 255 ? 2 : 1;
}
return n;
}
//Truncate the string according to the 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 search
if(!(str "").length || !len || len< ;=0){return "";}
if(this.getBlength(str) <= len){return str;} //The most time-consuming judgment in the entire function, welcome to optimize
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
}

Test the string above. The longer it is, the more time-consuming it is to load. Try cutting it to a length of 20W:
Copy code 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 starts-------------")
console.log("String. cutByte('1 starts with 1',6,'...') >> ",String.cutByte('1 starts with 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 starts--")
var time1 = new Date()
for(var i=0;i<100;i ){
String. cutByte(str,200000,'...')
}
console.log("Time consuming:",new Date() - time1);

Output result:

The length of the created string is: 314432 The byte length is: 425408
-------------Test begins------------- -
Copy code The code is as follows:

String.cutByte('1 starts with 1',6 ,'...') >> 1 starts 1
String.cutByte(str,12,'...') >> javascrip...
String.cutByte(str,13, '..') >> javascript ..
String.cutByte(str,14,'.') >> javascript high.
String.cutByte(str,15,'') > > javascript high

--Efficiency test starts--
Time consuming: 155

In fact, changing the intercepted character length to 30W and 40W will not be much different, In the face of the binary method, this is all on the same level

Compared with the previous time-consuming calculation of the byte length, using the binary method to search and intercept only consumes less than two byte length calculations.

Finally, students, come and challenge your efficiency!
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template