How can I use javascript to add "http://www." to the beginning of a URL that the user types in?
| SitePoint Sponsor |
How can I use javascript to add "http://www." to the beginning of a URL that the user types in?

Hi,
Could you tell us a little more about what you're trying to do?
For example what is the user typing the url in to?
A text field in a form?
Also, why do you need to prepend "http://www." to the url?
Some urls may not work with the "www." prepended to them, others might use the https protocol.
What about if the user types in just the "www."?
At a first glance, this sounds like it might be better done server-side.
Edit: For example, if you are using PHP you can use parse_url()
How well do you know your JavaScript from your jQuery?
Check out SitePoint's latest JavaScript challenge
My blog

OK, this'll do that:
Code JavaScript:<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Add 'http://' to text input</title> </head> <body> <form id="myForm"> <p> <label for="url">Please enter a URL:</label> <input type="text" id="url" /> </p> <input type="submit" value="Submit"> </form> <script> var f = document.getElementById('myForm'); f.onsubmit = function(){ var url = f.url.value; if(!url.match(/^http/)) { url = 'http://' + url; } alert('You entered: ' + url); } </script> </body> </html>
How well do you know your JavaScript from your jQuery?
Check out SitePoint's latest JavaScript challenge
My blog
Bookmarks