JavaScript 链接省略号

标签 javascript html

我有以下代码:

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

它用链接替换所有网址,但有些链接显示起来太长,这就是我想要的:

之前:

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

FIDDLE

关于JavaScript 链接省略号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35736980/

相关文章:

javascript - body 不会在溢出时滚动

javascript - 居中文件输入 Bootstrap

javascript - meteor 自动成型 : form with id "asdf" needs either "schema" or "collection" attribute

javascript - 在 ng-repeat 中显示字符串输出

javascript - Redux 防止不必要的渲染

java - 检查并插入缺少 alt 属性的图像

c# - 'OnCheckedChanged' 时 ASP.NET 更新网页

javascript - 重置 setInterval() 的定时器

javascript - xml 到 json 转换中不需要的字段?

javascript - 使用jquery将json导入到html输入字段