Intelligent URL Shortening
Made by Adam Schwartz.
HTML
<pre id="log"></pre>
CSS
* { font-family: monospace; font-size: 12px; }
.g { color: green; }
.r { color: red; }
JavaScript
$(function(){
var max_length = 45,
test_urls= {
'http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=blog+with+long+slugs':
'google.com/search?q=blog+with+long+slugs',
'http://www.google.com/images/search?sourceid=chrome&ie=UTF-8&q=blog+with+long+slugs':
'google.com/im../search?q=blog+with+long+slugs',
'http://sharepoint/sites/omss/Specs/Specs/Forms/AllItems.aspx?RootFolder=/sites/omss/Specs/Specs/SPW%20(Boston)&FolderCTID=0x012000F976F6C1137ABD4E826AD50F8C623B35007452B1EE46F01D428A0DE8FA05BB0E18':
'sharepoint/../omss/Specs/Specs/SPW%20(Boston)',
'https://mitsubishielectricgroup.sharepoint.com/sites/001315/GW/V679/SharedDocuments/Forms/AllItems.aspx?RootFolder=%2Fsites%2F001315%2FGW%2FV679%2FSharedDocuments%2FPPPoE%E7%96%91%E4%BC%BC%E3%82%B5%E3%83%BC%E3%83%90&':
'https://mitsubishielectricgroup.sharepoint.com/sites/001315/GW/V679/SharedDocuments/PPPoE疑似サーバ',
'http://this_url_will_intentionally_fail.com/':
'http://this_url_won\'t_fail.com/wait...what?'
};
function log(s) {
$('#log').append($('<div/>').html(s));
}
function run_tests() {
for (url in test_urls) {
var short = shorten(url);
log(
short == test_urls[url] ?
'<span class="g">Pass:<br/>'
+ url + ' -><br/>' + short + '<br/><br/>' +
'</span>' :
'<span class="r">Fail:<br/>'
+ short + ' !=<br/>' + test_urls[url] + '<br/><br/>' +
'</span>'
);
}
}
function shorten(url) {
var join_by = '',
last_part,
attempt = 0,
url_parts = [url,''];
while (true) {
if (url_parts[url_parts.length - 1] == '') {
url_parts.pop();
}
url = url_parts.join(join_by);
if (url.length <= max_length || attempt > 50) {
return url;
}
switch (attempt) {
case 0:
...