Javascript regular expression to add protocol to url string

I have an application to list some website details using JavaScript. There will be a link to website which is generated using JavaScript itself. Sometimes I will get my link as,

<a href="http://www.google.com">Website</a>

But sometimes it will be,

<a href="www.yahoo.com">Website</a>

In the second time the link is not working, there is no protocol.

So I am looking for a JavaScript regular expression function to add http:// if there in no protocol.

My code looks like,

var website_link = document.createElement("a"); 
website_link.innerHTML = "Website"; 
website_link.href = my_JSON_object.website;
website_link.target = "_blank"; 
profile.appendChild(website_link); 

And no local links will come.

Answers


See this link.

function setHttp(link) {
    if (link.search(/^http[s]?\:\/\//) == -1) {
        link = 'http://' + link;
    }
    return link;
}
alert(setHttp("www.google.com"));
alert(setHttp("http://www.google.com/"));  

In your code it will be like:

var website_link = document.createElement("a"); 
website_link.innerHTML = "Website";
if (my_JSON_object.website.search(/^http[s]?\:\/\//) == -1) {
    my_JSON_object.website = 'http://' + my_JSON_object.website;
}
website_link.href = my_JSON_object.website;
website_link.target = "_blank"; 
profile.appendChild(website_link); 

Need Your Help

.htaccess redirect direct access

apache .htaccess redirect

I'm trying to prevent users from directly accessing files on my website. Basically I have an image located in /images/header.jpg

Create Eloquent model from complex raw SQL-query

mysql laravel laravel-5 eloquent laravel-5.1

I am thinking about the right design of the method which gives user a list of clients who's last appointment was long time ago.