0

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?

1
  • You've created an XSS hole. Commented Jan 16, 2013 at 19:56

2 Answers 2

4
$(this).text(...)

You're setting the text of the element.

To set HTML, call .html().

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.