1

I have a db with a buch of urls. The values were entered by users, so it might be something like www.domain.com or http://www.domain.com or stackoverflow.com or https://something.com I'm retrieving that data and creating links in a html page so people can click and be redirected to that url. If i get the url from the page , i'll have either:

1.<a href="www.domain.com">

or

2.<a href="http://www.domain.com">

in the second case it works, but the first it doesn't. Is there a way to make it always work?

thanks!

George Cummins
  • 28,485
  • 8
  • 71
  • 90
blic
  • 103
  • 1
  • 9
  • If you using PHP, this might be helpful: [How to add http:// if it's not exists in the URL?](http://stackoverflow.com/questions/2762061/how-to-add-http-if-its-not-exists-in-the-url) If not, you can use javascript or you should specify server side language. You can't handle this with only HTML. – Wesley Murch Jan 26 '12 at 22:14

3 Answers3

1

The www. bit is not special at all, people rely on an automatic correction feature of most browsers to prepend it if the host does not exist. To replicate this, you need to run a program that attempts to resolve each of the host names in your database, and retries with an extra www. if that fails.

The http:// bit is easy: if it is missing, add it.

Simon Richter
  • 28,572
  • 1
  • 42
  • 64
  • thanks! i was afraid that might be the way to go.. I'll see how I'll make that work. – blic Jan 27 '12 at 03:06
0

For posterity, use href="//www.domain.com". It'll use keep whatever scheme (http: or https:) the current page is on. No need for JS.

<a href="//www.google.com">Link</a>
ShortFuse
  • 5,970
  • 3
  • 36
  • 36
0

There are two ways to handle this situation:

First, validate the user input. At the time a URL is submitted, validate it (preferably on the client side via Javascript) to ensure it has the required elements.

Second, in your code, you can use a regular expression or even simple pattern matching to ensure that the string starts with 'http://' or 'https://', and prepend it as needed.

The implementation details vary from language to language, but the concept is the same.

George Cummins
  • 28,485
  • 8
  • 71
  • 90