2

I want to replace a link as plain text format to html format.

But I got the issue that, I don't know how to prepend the http:// prefix for the new replacement if in the original link does not exist.

var text        = "google.com and http://google.com";
var pattern     = /(\b((https?)\:\/\/)?[A-Za-z0-9]+\.(com|net|org))/ig;
text            = text.replace(pattern,"<a href='$1'>$1</a>");

I meant:

  1. If: google.com will be replaced <a href="http://google.com">google.com</a>
  2. If: http://google.com will be replaced <a href="http://google.com">http://google.com</a>
2
  • 1
    Just so you know.. www.google.com is not handled by your regex Commented Dec 28, 2011 at 4:21
  • I just want to make my question is as simple as. :D Commented Dec 28, 2011 at 6:06

1 Answer 1

3

Use the overload of String.replace that takes a function:

var text = "google.com and http://google.com";
var pattern = /(\b((https?)\:\/\/)?[A-Za-z0-9]+\.(com|net|org))/ig;

text = text.replace(pattern, function (str, p1)
{
    var addScheme = p1.indexOf('http://') === -1
                    && p1.indexOf('https://') === -1;

    return '<a href="' + (addScheme ? 'http://' : '') + p1 + '">' + p1 + '</a>';
});

// text is:
// '<a href="http://google.com">google.com</a> and <a href="http://google.com">http://google.com</a>'
Sign up to request clarification or add additional context in comments.

1 Comment

And @parapura rajkumar is correct; the regex will not handle www.google.com (really, any subdomains), so you might want to fix that.

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.