I would like to display a URL in a table while restricting it to a specific length. Being a URL, it would be nice to preserve the most meaningful parts which tend to be the beginning and end. This functionality can be seen when viewing long URLs in the Firebug 'Net' panel.
问题:
回答1:
This is a quick and dirty solution but it has been working well for me so far and can be easily updated to any individual preferences. It's broken into two functions for readability and reuse.
This function makes use of the shortString
function shown below. It shortens a URL to less than or equal to the specified length (l) while preserving the beginning and end of the URL and truncating at preferred characters (' ', '/', '&').
function shortUrl(url, l){
var l = typeof(l) != "undefined" ? l : 50;
var chunk_l = (l/2);
var url = url.replace("http://","").replace("https://","");
if(url.length <= l){ return url; }
var start_chunk = shortString(url, chunk_l, false);
var end_chunk = shortString(url, chunk_l, true);
return start_chunk + ".." + end_chunk;
}
This function starts at the beginning of a string (or end, if reverse=true) and, once it reaches an acceptable length, starts looking for preferred stop characters to truncate at. If no stop characters are found before the specified length (l) is reached, the string is returned truncated to the max length.
function shortString(s, l, reverse){
var stop_chars = [' ','/', '&'];
var acceptable_shortness = l * 0.80; // When to start looking for stop characters
var reverse = typeof(reverse) != "undefined" ? reverse : false;
var s = reverse ? s.split("").reverse().join("") : s;
var short_s = "";
for(var i=0; i < l-1; i++){
short_s += s[i];
if(i >= acceptable_shortness && stop_chars.indexOf(s[i]) >= 0){
break;
}
}
if(reverse){ return short_s.split("").reverse().join(""); }
return short_s;
}
Example
>>> var url = "http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/"
>>> shortUrl(url)
"blog.stackoverflow.com/..swer-your-own-questions/"
回答2:
I have a very simple solution. I had a similar requirement for a dashboard page:
"We need a URL shortener function that returns a 50 character string, the beginning without http or https and include 32 characters, then an ellipsis, and then the last 15 characters."
So, the shortUrl function needed to take in the long URL, Get the last 15 characters - slice from long url's length (same as last character) minus 15 to get start of slice to the end. Clip off http/https start - I used replace(), Get the next 32 characters - substr(), and then Return new start + ellipsis (...) + end:
var shortUrl = function(u) {
uend = u.slice(u.length - 15);
ustart = u.replace('http://', '').replace('https://', '').substr(0, 32);
var shorter = ustart + '...' + uend;
alert(shorter);
return shorter;
}
var longUrl = 'http://www.somekoolsite.com/subsite/subsubsite/morefolders/andetc/page.php';
shortUrl(longUrl);
// Result: "www.somekoolsite.com/subsite/sub...andetc/page.php"
回答3:
I have created a method to work both for urls and url-encoded local file paths.
function pathShorten (str, maxLength, removeFilename) {
var splitter = str.indexOf('/')>-1 ? '/' : "\\",
tokens = str.split(splitter),
removeFilename = !!removeFilename,
maxLength = maxLength || 25,
drive = str.indexOf(':')>-1 ? tokens[0] : "",
fileName = tokens[tokens.length - 1],
len = removeFilename ? drive.length : drive.length + fileName.length,
remLen = maxLength - len - 5, // remove the current lenth and also space for 3 dots and 2 slashes
path, lenA, lenB, pathA, pathB;
//remove first and last elements from the array
tokens.splice(0, 1);
tokens.splice(tokens.length - 1, 1);
//recreate our path
path = tokens.join(splitter);
//handle the case of an odd length
lenA = Math.ceil(remLen / 2);
lenB = Math.floor(remLen / 2);
//rebuild the path from beginning and end
pathA = path.substring(0, lenA);
pathB = path.substring(path.length - lenB);
path = drive + splitter + pathA + "..." + pathB + splitter ;
path = path + (removeFilename ? "" : fileName);
// console.log(tokens, maxLength, drive, fileName, len, remLen, pathA, pathB);
return path;
}
Some examples:
pathShorten("http://ok.some-bookshop.co.uk/books/horror/find.php?q=urge",35,false)
"http://ok.s...orror/find.php?q=urge"
pathShorten("http://ok.some-bookshop.co.uk/books/horror/find.php?q=urge",35,true)
"http://ok.some-book...books/horror/"
pathShorten("file:///C:/Users/johpan/OneDrive/Shared%20favorites/show must go on.mp3",55,false)
"file:///C:/Users/jo...d%20favorites/show must go on.mp3"
pathShorten("file:///C:/Users/johpan/OneDrive/Shared%20favorites/show must go on.mp3",55,true)
"file:///C:/Users/johpan/OneDr...ive/Shared%20favorites/"