JavaScript efficiently intercepts strings by byte

Source: Internet
Author: User
Tags date end extend log return string

As a front-end developer in the Web display often encounter, the title is too long, need to intercept the string, with the implementation of CSS various compatibility problems, various pits.

Let the background program, and a variety of Dodge, let the background by byte cut more is and want to the backstage, the end may only the character length to you cut, finally not good-looking, not neat, or back to the whole CSS, tune compatible;

There are more than the feelings of the front end students silently point a praise bar.



Recently contacted a project, backstage only provides the interface (JSON), all pages of data rendering, data binding to the front end. Finally, regardless of SEO, the page all the initiative to my hands, inadvertently encountered byte intercept old problem.

A JavaScript is a simple way to get byte lengths on the Web:

String.prototype.Blength = function () {//return string byte length
return This.replace (/[^\x00-\xff])/g, "AA"). Length;
};

It is really very simple, more than ASCII characters are counted as two bytes, although not strictly correct, but we are used to help show the effect, really strict but not good,

But the total feeling for a bit of opportunistic, and the more time-consuming things are not too good, in fact, it will save two lines of code, so I decided to still use the normal way to calculate:

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 a string image, or because of the efficiency problem, here is the test code:


Extend to prototype on 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 to the image
String.getblength = function (str) {
for (var i = str.length, n = 0; i--;) {
n + = str.charcodeat (i) > 255? 2:1;
}
return n;
}
First, construct a long string of Chinese-English mixed
var str = "JavaScript efficient byte-intercept string method Getblengthjavascript efficient byte-intercept string method Getblength";
str = str.replace (/./g, str). replace (/./g, str);
Console.log ("Created string length is:", str.length)
Console.log ("-------------Test start--------------")
Console.log ("str.") Blength () >> ", str. Blength ())
Console.log ("String.getblength (str) >>", String.getblength (str))
Console.log ("--efficiency Test start-")

var time1 = new Date ()
for (Var i=0;i<100;i++) {
Str. Blength ()
}
Console.log ("Blength Time Consuming:", new Date ()-time1);

var time2 = new Date ()
for (Var i=0;i<100;i++) {
String.getblength (str)
}
Console.log ("Getblength Time Consuming:", new Date ()-time2);



The result of inefficient is not 1:30, as the reason may be spent in the prototype chain of the search, I did not delve into, know can leave a message to tell me:


The length of the string created is: 314432
-------------Test started--------------
Str. Blength () >> 425408
String.getblength (str) >> 425408
--The efficiency test begins--
Blength Time Consuming: 1774
Getblength Time consuming: 95



The basic function to intercept the string now has, because in this case the character occupies the longest byte length of 2, so it is better to use the binary to find the right intercept location.

An intercept function that is supposed to be a good efficiency:




Simple compute byte length
String.getblength = function (str) {
for (var i = str.length, n = 0; i--;) {
n + = str.charcodeat (i) > 255? 2:1;
}
return n;
}
Intercepts a string by the specified byte
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)}//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, welcome to the optimization
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 string above to test, it should be loaded longer and more time-consuming, truncated 20W length try:


Console.log ("Created string length:", str.length, "byte length is:", String.getblength (str))
Console.log ("-------------Test start--------------")
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 start-")
var time1 = new Date ()
for (Var i=0;i<100;i++) {
String.cutbyte (str,200000, ' ... ')
}
Console.log ("Time Consuming:", new Date ()-time1);



Output results:


The length of the string created is: 314432 bytes Length: 425408
-------------Test started--------------
String.cutbyte (' 1 start 1 ', 6, ' ... ') >> 1 start 1
String.cutbyte (str,12, ' ... ') >> javascrip ...
String.cutbyte (str,13, ' ... ') >> JavaScript.
String.cutbyte (str,14, '. ') >> JavaScript high.
String.cutbyte (str,15, ') >> JavaScript high
--The efficiency test begins--
Time consuming: 155



In fact, to change the length of the intercept character to 30W 40W time is not much worse, in the face of the second, this is a level of

Compared to the time elapsed before the length of the computed byte, the binary is used to find the length of the intercept which consumes less than two bytes.



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.