开发者

Problems with rewriting href values with jquery

I'm trying to handle urls in plain text.

For now im able to target and rewrite www.null.com/foo/bar into an href with the same href and value as the string it self.

(Thanks Steve Reynolds http://bit.ly/Xk5Hc)

$("#topcontent p").each(function(){
    var newHT开发者_运维百科ML;
    var stringInput = $(this).html();
    newHTML = replaceURLWithHTMLLinks(stringInput);     
    $(this).html(newHTML).find('a').addClass('highlite');
});

function replaceURLWithHTMLLinks(text) {
    var exp = /(www[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp,"<a href=http://$1>$1</a>");
}

Now then. Is there a way to modify the anchortag so that the value of it shortens down to .com instead of .com/foo/bar?

<a href="http://www.null.com/foo/bar">www.null.com</a>


it is easier if you just do a function to return just the cleaned html, so:

function replaceURLWithHTMLLinks(text) {
    var exp = /(www[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp,"$1");
}

and then just add the href and html separate:

href = replaceURLWithHTMLLinks(stringInput);
var link = $(document.createElement('a')).attr('href', 'http://'+href)
              .addClass('highlite')
              .html(href.replace(/\/[^.]+$/gi, ''));
$(this).html(link);

that will just create a new link object, add the correct href you return with your function and then replaces all ending non-dot characters with '' (in your case this will always be the /foo/bar)

Also, this is a lot better than your previous example because it is less javascript intensive (you don't have to find the 'a' again and then modify its properties, you just create one with those properties from the start)


Does this work?

Regex: a href=["']*http:\/\/([a-zA-Z0-9+&@#%=~_|.]+)

http://www.rubular.com/r/6UNlh52T86


var exp = /(www[-A-Z0-9+&@#%?=~_|!:,.;]*[-A-Z0-9+&@#%=~_|])([-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])?/ig;

This will match and therefore replace only the section before the first '/' though it will capture the rest as well, leaving you with:

<a href="http://www.null.com">www.null.com</a>

Edit: Fixed problem with URLs without anything afterwards. Verified in jsFiddle.net

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜