I have the following strings
http://example.com
https://example.com
http://www.example.com
how do i get rid of the http:// or https://?
I have the following strings
http://example.com
https://example.com
http://www.example.com
how do i get rid of the http:// or https://?
You may use URL() constructor. It will parse your url string and there will be an entry w/o protocol. So less headache with regexps:
let u = new URL('https://www.facebook.com/companypage/');
URL {
hash: ""
host: "www.facebook.com"
hostname: "www.facebook.com"
href: "https://www.facebook.com/companypage/"
origin: "https://www.facebook.com"
password: ""
pathname: "/companypage/"
port: ""
protocol: "https:"
search: ""
searchParams: URLSearchParams {}
username: ""
}
u.host // www.facebook.com
u.hostname // www.facebook.com
Although URL() drops out a protocol, it leaves you with www part. In my case I wanted to get rid of that subdomain part as well, so had to use to .replace() anyway.
u.host.replace(/^www./, '') // www.facebook.com => facebook.com
Using regex might be an overkill when there's a handy native URL interface that does the job for you in 2 lines:
let url = "https://stackoverflow.com/questions/3999764/taking-off-the-http-or-https-off-a-javascript-string";
let a = new URL(url);
let withoutProtocol = a.host+a.pathname;
console.log(`Without protocol: ${withoutProtocol}`);
console.log(`With protocol: ${url}`);