Javascript text formatting

How can I use javascript to add “http://www.” to the beginning of a URL that the user types in?


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()

I have a forum where the user needs to enter a URL and I want JavaScript to add “http://” if the user doesn’t.

OK, this’ll do that:

<!DOCTYPE html>
    <meta charset="utf-8" />
    <title>Add 'http://' to text input</title>
    <form id="myForm">
        <label for="url">Please enter a URL:</label>
        <input type="text" id="url" />
      <input type="submit" value="Submit">
    var f = document.getElementById('myForm');
    f.onsubmit = function(){
      var url = f.url.value;
      if(!url.match(/^http/)) {
        url = 'http://' + url;
      alert('You entered: ' + url);