在提供的字符串中设置锚标记

时间:2011-06-07 11:45:31

标签: javascript jquery anchor

我想在提供的字符串中设置锚标记。它在http://之后在javascript中搜索并将其设置为锚标记。

function createLink(text, node){//text is the provided string
    var start = text.indexOf('http://');
    var end = text.indexOf(' ', start) + 1 || text.length - 1; //provides 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);
}

1 个答案:

答案 0 :(得分:0)

我认为你离开了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/