JavaScript链接省略号

StratHaxxs

我有以下代码:

function urlify(text) {
    var urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, function(url) {
        return '<a href="' + url + '">' + url + '</a>';
    })
    // or alternatively
    // return text.replace(urlRegex, '<a href="$1">$1</a>')
}
function dome() {
    var desc = document.getElementById('eow-description');
    desc.innerHTML = urlify(desc.innerHTML);
}

它用链接替换了所有的url,但是有些链接很长,很难显示出来,这就是我想要的:

前:

My version of a Five Guys Cheeseburger! Super easy to make at home with the same results as the original.<br>
Ballistic BBQ on Facebook: https://www.facebook.com/BallisticBBQ
Weber Performer: http://www.amazon.com/gp/product/B0098HR1I0/ref=as_li_tl?ie=UTF8&camp=211189&creative=373489&creativeASIN=B0098HR1I0&link_code=as3&tag=babb0f-20&linkId=KNX2BA5WT32WIBWU
Craycort Grate: http://www.amazon.com/gp/product/B004BRNUIC/ref=as_li_tl?ie=UTF8&camp=211189&creative=373489&creativeASIN=B004BRNUIC&link_code=as3&tag=babb0f-20&linkId=JY5PJ6AMEZYANRUP
Craycort Hotplate: http://www.amazon.com/gp/product/B0088NR4NC/ref=as_li_tl?ie=UTF8&camp=211189&creative=373489&creativeASIN=B0088NR4NC&link_code=as3&tag=babb0f-20&linkId=FZJDNBTU7BYQMSJB

后:

My version of a Five Guys Cheeseburger! Super easy to make at home with the same results as the original.
Ballistic BBQ on Facebook: https://www.facebook.com/BallisticBBQ
Weber Performer: http://www.amazon.com/gp/...
Craycort Grate: http://www.amazon.com/gp/...
Craycort Hotplate: http://www.amazon.com/...
阿德内

您可以修改urlify功能并添加一个slice()

function urlify(text, maxlength) {
    var urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, function(url) {
        var u = url.length > maxlength ? url.slice(0, maxlength) + '&hellip;' : url;
        return '<a href="' + url + '">' + u + '</a>';
    });
}

function dome() {
    var desc = document.getElementById('eow-description');
    desc.innerHTML = urlify(desc.innerHTML, 25);
}

小提琴

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章