How to Replace HTTP with HTTPS in a String URL Using JavaScript?

In this article, we will see ways in which you can force https scheme instead of http in a JavaScript string containing a url. For all examples in this article, let's suppose we have the following url:

const url = '';

Replacing the URL Scheme Using Regular Expressions

Using a regular expression, we can check whether a string starts with http:// or not, and accordingly, using replace(), we can replace it with https://. For example:

const updatedURL = url.replace(/^http:\/\//i, 'https://');

// output: ''

This would only replace to https:// when a string starts with http:// (case-insensitive), otherwise the original string is returned as is. To demonstrate this, let's see what happens when we use the same regular expression with a few other test cases:

Test Case Result
"" ""
// //
news:// news://

Browser Support:

JavaScript String.prototype.replace() has great browser support — it is supported in all browsers (new and old).

Replacing the protocol Property of the URL Object

The protocol property of the JavaScript URL object contains the scheme of the URL (including the final ":"). For example:

const url = new URL('');

console.log(url.protocol); // output: 'http:'

The protocol property can be modified by simple assignment. Therefore, we can replace http: protocol (if it exists in the url) with https: like so:

const urlObj = new URL(url);

if (urlObj.protocol === 'http:') {
    urlObj.protocol = 'https:';

// output: ''

As you can see from the example above, the protocol is updated in the resulting url. This is reflective of the internal changes in the object itself, for example:


/* output: [object URL] {
  hash: "#fragment",
  host: "",
  hostname: "",
  href: "",
  origin: "",
  password: "",
  pathname: "/path/",
  port: "",
  protocol: "https:",
  search: "?key=value",
  // ...

Regardless of the case of the protocol passed into the URL object (or set by direct assignment), you can expect the resulting string from url.protocol to always be lowercase (unless the browser implementation does not adhere to RFC 1738 — in which case you can do urlObj.protocol.toLowerCase() when doing comparisons, etc.).

Browser Support:

The URL object is very well supported in modern browsers, but lacks support in Internet Explorer. If that's a concern, then please consider replacing the URL scheme using regular expressions instead.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.