0

Currently I have a form in which you must enter a valid URL, although I don't have a way of validating that it ends in a extension such as .com or .co.uk etc..

Here's my current function which makes sure it's a http://

function addhttp(url) {
    if (!/^(f|ht)tps?:\/\//i.test(url)) {
            url = "http://" + url;
    }
    return url;
}

I can't find a way to verify the end of the url variable to make sure its a .com etc...

Curtis
  • 2,646
  • 6
  • 29
  • 53
  • Possible duplicate of [How to parse a URL?](http://stackoverflow.com/questions/6168260/how-to-parse-a-url) – Heretic Monkey Mar 21 '17 at 18:25
  • 1
    A "valid URL" doesn't *need* to end in a TLD extension. – David Mar 21 '17 at 18:25
  • You might want to look at https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains before deciding that you want to verify that the domain ends with one of several hundred different possibilities... And that is just the top level ones. If you want things like .co.uk and .org.uk and all the next level down possibilities then... Well, have fun. – Chris Mar 21 '17 at 18:44

1 Answers1

0

You can utilize the end-of-string character $ in your regex to match what's at the end of a string, and put your match criteria before it:

if (/\.(co(\.(uk))?|com|org|net)\/?$/i.test(url)) {
    //Do something with the URL
}

This example matches .co, .com, .org, .net, .co.uk, and any of the previous with an ending /. Of course, you can tailor it to whatever endings you want to cover.

J. Titus
  • 9,535
  • 1
  • 32
  • 45