2

我想在表格中显示一个 URL,同时将其限制为特定长度。作为一个 URL,最好保留最有意义的部分,这些部分往往是开头和结尾。在 Firebug 'Net' 面板中查看长 URL 时可以看到此功能。

4

3 回答 3

5

这是一个快速而肮脏的解决方案,但到目前为止它对我来说效果很好,并且可以轻松更新为任何个人偏好。为了可读性和重用性,它分为两个功能。

该函数使用shortString如下所示的函数。它将 URL 缩短为小于或等于指定长度 (l),同时保留 URL 的开头和结尾并截断首选字符(''、'/'、'&')。

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;
}

此函数从字符串的开头(或结尾,如果 reverse=true)开始,一旦达到可接受的长度,就会开始寻找要截断的首选停止字符。如果在达到指定长度 (l) 之前没有找到停止字符,则返回的字符串被截断为最大长度。

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;
}

例子

>>> 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/"
于 2012-06-05T18:43:24.657 回答
4

我有一个非常简单的解决方案。我对仪表板页面有类似的要求:

“我们需要一个 URL 缩短器函数,它返回一个 50 个字符的字符串,开头没有 http 或 https,包含 32 个字符,然后是省略号,最后是 15 个字符。”

因此,shortUrl 函数需要获取长 URL,获取最后 15 个字符 - 从长 url 的长度(与最后一个字符相同)减去 15 以获取切片的开头到结尾。剪掉 http/https 开始 - 我使用了 replace(),获取接下来的 32 个字符 - substr(),然后返回新的开始 + 省略号 (...) + 结束:

 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"

于 2015-02-01T02:05:36.683 回答
1

我已经创建了一种方法来处理 url 和 url 编码的本地文件路径。

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;
}       

一些例子:

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/"
于 2019-06-16T13:09:58.487 回答