I received a request today:
1. Give a text, intercept the output text, and keep 400 characters.
2. If the intercepted content is a URL, keep the complete URL address.
3. Add an ellipsis. .....
----
It is more troublesome to retain the URL, especially when there are two identical URLs, indexOf cannot be used to obtain their character positions.
Processing result:
Related code:
String.prototype.sizeAt = function(){
var nLen = 0;
for(var i = 0, end = this.length; inLen = this.charCodeAt( i)>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;inLen = this.charCodeAt(i)>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;
//Find all contained urls
var aUrl = s.match(/https?://[a-zA-Z0-9] (.[a-zA-Z0-9] ) ([-_A-Z0-9a-z$. !*/ ,:;@&=?~#%]*)*/gi);
//When the max character is exactly between urls, bCut will be set to flase;
var bCut = true;
if(aUrl){
//Judge each url
for(var i=0, endI = aUrl.length;ivar sUrl = aUrl[ i];
//Two identical URLs may occur
var aP = s.split(sUrl);
var nCurr = 0;
var nLenURL = sUrl.sizeAt();
var sResult = "";
for(j = 0, endJ = aP.length; jnCurr =aP[j].sizeAt();
sResult =aP [j];
sResult = sUrl;
//The current word count is less than max but adding the url exceeds max: the url will be intercepted
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('Normal interception of 20 characters'.cutStrButUrl(20,'...'));
console.log('Normal interception of 20 characters, But I exceeded '.cutStrButUrl(20,'...'));
console.log('Can you intercept the string with url 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, '...'));