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; //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/
精彩评论