taking off the http or https off a javascript string

前端 未结 12 1583
面向向阳花
面向向阳花 2020-12-20 11:23

I have the following strings

http://example.com
https://example.com
http://www.example.com

how do i get rid of the http:// or

12条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-20 12:06

    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
    

提交回复
热议问题