2016-03-02 72 views
0

我有以下代码:JavaScript的链接省略号

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,但有些链接是wayyy长显示,这是我想它做的事:

之前:

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/... 

回答

3

您可以修改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); 
} 

FIDDLE

+0

@DavidThomas - 当然,我知道这件事情,但从来没有使用它,它只是总是容易键入三个时期。 – adeneo

+0

@DavidThomas谢谢,伙计们! – StratHaxxs