· JavaScript  · 1 min read

JavaScript Remove http or https from URL

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.

Share:
Back to Blog

Related Posts

View All Posts »
Higher-Order Functions in JavaScript

Higher-Order Functions in JavaScript

JavaScript higher-order functions let you treat functions like values—passing them as arguments, returning them, or storing them in variables.