问题描述:

I'm trying to replace text by html tags. I'm using this code:

 $('p').each(function () {

$(this).text($(this).text().replace(/(http:\/\/.+?)(\s|$)/g, function(text, link) {

return '<a href="'+ link +'" target="blank">'+ link +'</a>';

}).replace(/(www\..+?)(\s|$)/g, function(text, link) {

return '<a href="http://'+ link +'" target="blank">'+ link +'</a>';

})

);

});

But the problem is that it's not replacing the text by html, but by another text.

For example:

 www.google.com

becomes (still in text):

 <a href="http://www.google.fr" target="blank">www.google.fr</a>

Any idea on how I could solve that?

网友答案:
$(this).text(...)

You're setting the text of the element.

To set HTML, call .html().

网友答案:

use .html() :

 $('p').each(function () {
    $(this).html($(this).text().replace(/(http:\/\/.+?)(\s|$)/g, function(text, link) {
               return '<a href="'+ link +'" target="blank">'+ link +'</a>';
            }).replace(/(www\..+?)(\s|$)/g, function(text, link) {
               return '<a href="http://'+ link +'" target="blank">'+ link +'</a>';
                })
            );  
        });

Working Demo

相关阅读:
Top