Home > Web Front-end > JS Tutorial > body text

In js, strings are intercepted based on the number of words, but url_javascript tips cannot be intercepted

WBOY
Release: 2016-05-16 17:57:22
Original
1121 people have browsed it

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:
Copy code The code is as follows:

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, '...'));
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