Ayyoudy
Ayyoudy

Reputation: 3721

HTML force URL hyperlink to be treated as non-relative (absolute)

I have a list of URLs that our users have entered for websites of various clients... I am loading this list from the server into a grid for the users to see... I made the URLs clickable by wrapping them with a href HTML tag... the problem is, sometimes the user enters urls without the http:// or www. prefix and so the browser treats them as relative URLs which are never ever the case because all these websites are for our clients and they are all external. Is there a way to force these URLs to be treated as absolute instead of relative?

Here is an example:

<a target='_blank' href='google.com'>google.com</a>

If you try this, you'll see that the browser will assume it is a relative path which shouldn't be the case.

Thanks


Solution:

I've chosen to check for '//' (because I don't know what the protocol is - could be http or https) and if not found, I assume it is an http website and I prefix the URL with that - so in short no way to force the browser to treat the hyperlinks as absolute

Upvotes: 31

Views: 21067

Answers (3)

sedrakpc
sedrakpc

Reputation: 564

You can add // before the url and it should work.

Like: //stackoverflow.com

Upvotes: 31

Quentin
Quentin

Reputation: 944530

It is a relative URI.

If you want to link to http://google.com/ then that is where you need to link to.

You can either moderate the URIs you are wrapping, or try to algorithmically guess if it was intended to be a relative link or not.

Note that you cannot safely assume that there should be a www. since the use of that for websites is just a convention, and no longer a strongly followed one.

Upvotes: 0

Navneeth G
Navneeth G

Reputation: 7305

Why don't you preprocess the input and append http:// when necessary?

Upvotes: 8

Related Questions