Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 887
Anshad Vattapoyil Avatar asked Feb 26 '26 18:02

Anshad Vattapoyil


1 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); 
like image 143
ostapische Avatar answered Mar 01 '26 07:03

ostapische



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!