简体   繁体   中英

set anchor tag in a provided string

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM