Moons
Moons

Reputation: 3854

JavaScript Regex for URL when the URL may or may not contain HTTP and WWW

I am using JavaScript regex that will check for the URL.

(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))

I use this Regex to send messages to Twitter. What happens is that this makes sure that the URL contains WWW and/or HTTP.

But the problem is if the URL is like Guaridan.com.uk Twitter consideres it as a URL.

So how can I modify my Regex that it will not check for HTTP or WWW, meaning if it is there then it would not take any effect.

So it would match like My.co.com or dummy.com.in.

Upvotes: 0

Views: 2062

Answers (3)

Try This...

/^http:\/\/|(www\.)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/

It's working exactly what peoples are want.

it takes with or with out http://, https://, and www.

Upvotes: 0

miss shaikh
miss shaikh

Reputation: 11

jQuery regular expression for www and http URL format.

Regular expression that accept www as well as http URL is given below:

var pattern = /(?:https?:\/\/)?(?:www\.)?(?:https?:\/\/)?(?:www\.)(?:https?:\/\/)?(?:www\.)?(\/\S*)?/;

Regular expression that accept www, http, abc.com is given below:

var pattern = ([\d\w]+?:\/\/)?([\w\d\.\-]+)(\.\w+)(:\d{1,5})?(\/\S*)?

Upvotes: 1

pakopa
pakopa

Reputation: 683

If you want to match just domain names you have to match almost any word plus ".", "_" and "-" signs. An approach may be match at least the root domains (.com,.net,.us,.co.uk,.es,.fr ... and so on) but the list will be huge. You may want to match just anything that has dot separated words, not that it is going to be a domain for sure but you might try connecting to it.

This regex: ([\d\w]+?:\/\/)?([\w\d\.\-]+)(\.\w+)(:\d{1,5})?(\/\S*)?

will match:

  • group 1 as protocol:// (optional)
  • group 2 concat group 3 as domain
  • group 3 is the top level domain
  • group 4 as :port (optional)
  • group 5 as query (optional)

Upvotes: 1

Related Questions