Sheehan Alam
Sheehan Alam

Reputation: 60859

How can I check if a string contains a URL in javascript?

What is the regex pattern to determine if a URL exists in a string?

I would like to check for:

http://mydomain.com

and

http://www.mydomain.com

Upvotes: 0

Views: 7715

Answers (4)

Alexey Lebedev
Alexey Lebedev

Reputation: 12197

If's not quite clear whether you want to check for specific domain or just any domain.

  1. Checking for any domain in the form of http://domain.com or www.domain.com:

    /(http:\/\/|www\.)\S+/i.test(yourString)

  2. Checking for specific mydomain.com:

    /http:\/\/(www\.)?mydomain\.com/i.test(yourString)

Upvotes: 3

ap2cu
ap2cu

Reputation: 69

You can try the following javascript code:

if(new RegExp("[a-zA-Z0-9]+://([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?").test(myUrl)) {
  // TODO
}

Indeed the real full regex for a URL is:

[a-zA-Z\d]+://(\w+:\w+@)?([a-zA-Z\d.-]+\.[A-Za-z]{2,4})(:\d+)?(/.*)?

If you want, you can test 2 sites:

  1. a regex tester
  2. a javascript tester

I hope it will help you.

Upvotes: 1

Vinod R
Vinod R

Reputation: 1216

http://[a-z].[a-z].?[a-z].?[a-z]

You can get it tested at http://www.regexplanet.com/

Upvotes: 0

Jeremy Massel
Jeremy Massel

Reputation: 2267

if you know the domain ahead of time, you can do


if(myString.indexOf("http://mydomain.com") != -1)
{
//substring found, do stuff
}

see more here: http://www.w3schools.com/jsref/jsref_IndexOf.asp

If you don't know the domain ahead of time, regular expressions are probably your best bet

Upvotes: 0

Related Questions