2
String.prototype.linkify = function() {
this.replace(/((ht|f)tp:\/\/)?([^:\/\s]+)\w+.(com|net|org)/gi, '<a href="$&">$&</a>')
}

with http://www.google.com http://yahoo.com www.facebook.com it matches them all, however I want facebook to be prepended with the protocol group if it does not exist. Is there a way to do this without doing two .replace ?

2 Answers 2

1

I would do something like this:

String.prototype.linkify = function () {
  return this.replace(/((?:ht|f)tp:\/\/)?([^:\/\s]+\w+\.(?:com|net|org))/gi, function (_, protocol, rest) {
    var url = (protocol || "http://") + rest
    return '<a href="' + url + '">' + url + '</a>'
  })
}

(I fixed a couple of other problems with your code: you were missing a return and you were matching the domain name period using . rather than \..)

And I assume I don’t need to point out how poorly this will match URL:s in general, due to a number of problems with your pattern.

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

2 Comments

:how would your regex go? also, can you explain the parameters in the anonymous function in replace?
The parameters are simply $&, $1, $2. My idea of a good way to match URLs in general is outside the scope of this question, since it is actually a pretty hard problem. To put it simply, though, I would start with a complete list of all TLDs, and then match stuff ending in a TLD and having various fluff on either side (that’s easier once you realize that you have to start from the TLD).
1

If you don't actually need to match FTP URLs, you can just assume the "http://" section of the link. This regex does that, while allowing you to also use https.

this.replace(/(http(s)?:\/\/)?(([^:\/\s]+)\.(com|net|org))/gi,
                         '<a href="http$2://$3">http$2://$3</a>')

I'm not sure what your use case is, but I'd like to note this regex will fail on the following urls:

This is because you're using few hardcoded tlds (com, net, org), and aren't matching any characters after the domain.

1 Comment

Clever solution to making sure to grab https as appropriate.

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.