Adding http to url variable if missing

I’ve got some code where I need to check if a variable has http:// or https:// and if not, add http:// to the beginning of the var. I have tried some solutions online, but I wasn’t able to get them to work. Could someone let me know how I could add this function? Here’s my code:

        //search shorthand
        const params = new URLSearchParams(window.location.search)
        
        //find url param from window location and make variable
        var url = params.get('url')
        
        //decode url
        var url = atob(url);
        

        //this is where I want to do the check and possibly add the http://


        //alert the result
        alert(url);

Also, if there are any best practices I should be following, please let me know how I can improve my code. Thanks!

You could put the url in an anchor element, from where you can gain all sorts of useful location information, including the protocol.

If it doesn’t have a suitable protocol, it gets tricky to decide what to do. Web pages are moving over to being https instead of http, and http at many places is not accepted any more.

The best that might be hoped for is to raise attention about the invalid url.

Yeah, but I figure if the website requires https, it will just redirect you anyways. I’ve seen some solutions using regex to check if the var has http or https in it, but I wasn’t able to get it to work.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.