简体   繁体   中英

Replace text by html. Jquery

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

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