I received a request today:
1. Extract the output text and retain 400 characters.
2. If the content to be intercepted is a url, the complete url address is retained.
3. Add a ellipsis ......
----
It is difficult to retain the url, especially when there are two identical URLs, indexOf cannot be used to obtain its character location.
Processing result:
Related code:Copy codeThe Code is as follows: String. prototype. sizeAt = function (){
Var nLen = 0;
For (var I = 0, end = this. length; I <end; I ++ ){
NLen + = this. charCodeAt (I) & gt; 128? 2:1;
}
Return nLen;
};
String. prototype. cutStr = function (n, sCut ){
If (this. sizeAt () <= n ){
Return this;
}
SCut = sCut | "";
Var max = n-sCut.sizeAt ();
Var nLen = 0;
Var s = this;
For (var I = 0, end = this. length; I <end; I ++ ){
NLen + = this. charCodeAt (I) & gt; 128? 2:1;
If (nLen> max ){
S = this. slice (0, I );
S + = sCut;
Break;
}
}
Return s. toString ();
};
String. prototype. cutStrButUrl = function (n, sCut ){
If (this. sizeAt () <= n ){
Return this. toString ();
}
SCut = sCut | "";
Var max = n-sCut.sizeAt ();
Var s = this;
// Search for all included URLs
Var aUrl = s. match (/https? : \ // [A-zA-Z0-9] + (\. [a-zA-Z0-9] +) + ([-_ A-Z0-9a-z \ $ \. \ + \! \ * \/, :;@&= \? \~ \ # \ %] *) */Gi );
// When the maximum character is between URLs, bCut is set to flase;
Var bCut = true;
If (aUrl ){
// Judge each url
For (var I = 0, endI = aUrl. length; I <endI; I ++ ){
Var sUrl = aUrl [I];
// There may be two identical URLs
Var aP = s. split (sUrl );
Var nCurr = 0;
Var nLenURL = sUrl. sizeAt ();
Var sResult = "";
For (j = 0, endJ = aP. length; j <endJ; j ++ ){
NCurr + = aP [j]. sizeAt ();
SResult + = aP [j];
SResult + = sUrl;
// The current number of words is less than max, but the number of words added to the url exceeds max.
If (nCurr <max & nCurr + nLenURL> max ){
S = sResult + sCut;
BCut = false;
Break;
}
NCurr + = nLenURL;
}
If (bCut = false ){
Break;
}
};
}
If (bCut ){
S = s. cutStr (n, sCut );
}
Return s. toString ();
};
Console. log ('20 characters intercepted normally '. cutStrButUrl (20 ,'......'));
Console. log ('20 characters are intercepted normally, but I have exceeded '. cutStrButUrl (20 ,'......'));
Console. log ('Can you truncate the url string http://www.baidu.com? '. CutStrButUrl (20 ,'......'));
Console. log ('HTTP: // www.baidu.com has two strings with the same url http://www.baidu.com? '. CutStrButUrl (51 ,'......'));