javascript - Shorten URL for display with beginning and end preserved (Firebug 'Net' panel style) -
i display url in table while restricting specific length. being url, nice preserve meaningful parts tend beginning , end. functionality can seen when viewing long urls in firebug 'net' panel.
this quick , dirty solution has been working me far , can updated individual preferences. it's broken 2 functions readability , reuse.
this function makes use of shortstring function shown below. shortens url less or equal specified length (l) while preserving beginning , end of url , truncating @ 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 @ beginning of string (or end, if reverse=true) and, once reaches acceptable length, starts looking preferred stop characters truncate at. if no stop characters found before specified length (l) reached, string returned truncated max length.
function shortstring(s, l, reverse){ var stop_chars = [' ','/', '&']; var acceptable_shortness = l * 0.80; // when start looking stop characters var reverse = typeof(reverse) != "undefined" ? reverse : false; var s = reverse ? s.split("").reverse().join("") : s; var short_s = ""; for(var i=0; < 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/"
Comments
Post a Comment