How to Remove http Protocol from URL using JavaScript

You can easily remove http:// (or https://) from a URL in JavaScript using a combination of string methods or regular expressions. Here are a few approaches:

Method 1: Using replace()

You can use the replace() method with a regular expression:

function removeHttp(url) {
    return url.replace(/^https?:\/\//, "");
}

// Example usage:
const url = "http://example.com";
const cleanUrl = removeHttp(url);
console.log(cleanUrl); // Output: example.com

Method 2: Using substring()

You can also use indexOf() and substring() if you prefer a more manual approach:

function removeHttp(url) {
    const httpIndex = url.indexOf("://");
    return httpIndex !== -1 ? url.substring(httpIndex + 3) : url;
}

// Example usage:
const url = "https://example.com";
const cleanUrl = removeHttp(url);
console.log(cleanUrl); // Output: example.com

Method 3: Using URL Object (for modern browsers)

You can utilize the URL object, which automatically handles various URL formats:

function removeHttp(url) {
    const parsedUrl = new URL(url);
    return parsedUrl.host; // or use parsedUrl.hostname
}

// Example usage:
const url = "http://example.com/path?query=1";
const cleanUrl = removeHttp(url);
console.log(cleanUrl); // Output: example.com

Any of these methods will effectively remove the http:// or https:// part of a URL. The choice of method can depend on your specific use case and whether you want to account for additional URL formats.