Skip to content

Instantly share code, notes, and snippets.

@aristretto
Last active December 12, 2015 10:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aristretto/4758583 to your computer and use it in GitHub Desktop.
Save aristretto/4758583 to your computer and use it in GitHub Desktop.
The purpose of this ditty is to truncate URIs in a more elegant way. ** I'm not a regex pro, be gentle :)
// truncate URIs in a more elegant way
String.prototype.truncateURI = function(n, backup){
var len = this.length;
var self = this.toString();
var max_len = (n||30);
var fallback = (backup||"website")
var patt = /^(https?\:\/\/)?(www\.)?([a-z0-9\-\_]+)([a-z\.]{2,})+([a-z0-9\-\_\#\/ ]+\/)?([a-z0-9\-\_\#\/]+\.?[a-z0-9]+)?/i
/*** PATTERN BREAKDOWN ***
// only handles relatively simple URIs for now
$0 everything
$1 scheme = ^(https?\:\/\/)?
$2 www ? = (www\.)?
$3 domain name = ([a-z0-9]+)
$4 domain suffix = ([a-z\.]{2,})+
$5 path(s) = ([a-z0-9\/ ]+\/)?
$6 final file/path = ([a-z0-9]+\.[a-z0-9]+)?
case insensitive = /i
::[todo]::
- queries & parameters
- more complex URIs
*/
// no truncation necessary
if(max_len >= len) return self;
// in case some unforseen URI gets passed in. We don't want everything to break;
try {
/** Step 1 **
try stripping protocol first */
if(self.replace(patt,"$2$3$4$5$6").length <= max_len){
return self.replace(patt,"$2$3$4$5$6");
}
/** Step 2 **
then try stripping wwww */
else if(self.replace(patt,"$3$4$5$6").length <= max_len){
return self.replace(patt,"$3$4$5$6");
}
/** Step 3 **
then replace filepath with /.../ */
else if(self.replace(patt,"$3$4/.../$6").length <= max_len){
return self.replace(patt,"$3$4/.../$6");
}
/** Step 4 **
then strip final file/path */
else if(self.replace(patt,"$3$4/...").length <= max_len){
return self.replace(patt,"$3$4/...");
}
/** Step 5 **
then strip domain suffix */
else if(self.replace(patt,"$3").length <= max_len){
return self.replace(patt,"$3");
}
/** Step 6 **
Give up & return "website" instead of original URL */
else {
return fallback;
}
} catch(err){
console.log(err);
return self;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment