开发者

set anchor tag in a provided string

开发者 https://www.devze.com 2023-03-12 00:34 出处:网络
I want to set a anchor tag in a provided string. It search in javascript after http:// and make it to an anchor tag.

I want to set a anchor tag in a provided string. It search in javascript after http:// and make it to an anchor tag.

function createLink(text, node){//text is the provided string
    var start = text.indexOf('http://');
    var end = text.indexOf(' ', start) + 1 || text.length - 1; //prov开发者_JAVA百科ides me with the wrong index
    var link = text.substring(start, end);
    var newLink = document.createElement('a');
    newLink.href = link;
    newLink.className = 'link';
    newLink.target = '_blank';
    newLink.innerHTML = link.substr(0, 20);
    if(link.length >= 20){
        $(newLink).append('...');
    }
    var head = text.substring(0, start);
    var tail = text.substring(end);
    node.innerHTML = '';
    $(node).append(head).append(newLink).append(tail);
}


I think you were off by 1:

function createLink(text, node){ //text is the provided string
    var start = text.indexOf('http://');
    var end = (text.indexOf(' ', start) + 1 || text.length - 1) - 1;
    var link = text.substring(start, end);

    var $a = $("<a>", {
        href: link,
        "class": "link",
        target: "_blank",
        html: link.substr(0, 20) + (link.length >= 20 ? "..." : ""),
    });

    var head = text.substring(0, start);
    var tail = text.substring(end);

    $(node).append(head).append($a).append(tail);
}

http://jsfiddle.net/hunter/vNrrR/

0

精彩评论

暂无评论...
验证码 换一张
取 消