taking off the http or https off a javascript string

前端 未结 12 1581
面向向阳花
面向向阳花 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

    This answer extends some answers above, http://, https://, or // which is also common.

    Thanks for answers above that led me to this!

    const urls = [ "http://example.com", "https://example.com", "//example.com" ]
    
    // the regex below states: replace `//` or replace `//` and the 'stuff'
    const resolveHostNames = urls.map(url => url.replace(/\/\/|.+\/\//, ''))
    
    console.log(resolveHostNames);
    

    Here's a link to a codepen.

    0 讨论(0)
  • Javascript use of split function also dervies the solution. Awesome !!!

    var url = "https://example.com";
    
    url = url.split("://")[1];    // for https use url..split("://")[0];
    console.log(url);
    
    0 讨论(0)
  • 2020-12-20 12:11
    var str = "https://site.com";
    
    str = str.substr( str.indexOf(':') + 3 );
    

    Instead of .substr(), you could also use .slice() or .substring(). They'll all produce the same result in this situation.

    str = str.slice( str.indexOf(':') + 3 );
    
    str = str.substring( str.indexOf(':') + 3 );
    

    EDIT: It appears as though the requirements of the question have changed in a comment under another answer.

    If there possibly isn't a http:// in the string, then do this:

    var str = "site.com";
    
    var index = str.indexOf('://');
    if( index > -1 )
       str = str.substr( index + 3 );
    
    0 讨论(0)
  • 2020-12-20 12:12
    var txt="https://site.com";
    txt=/^http(s)?:\/\/(.+)$/i.exec(txt);
    txt=txt[2];
    

    for parsing links without http/https use this:

    var txt="https://site.com";
    txt=/^(http(s)?:\/\/)?(.+)$/i.exec(txt);
    txt=txt[3];
    
    0 讨论(0)
  • 2020-12-20 12:12

    Assuming there are no double slashes other than the protocol, you could do:

     var url = "https://example.com";
     var noProtocol = url.split('//')[1];
    
    0 讨论(0)
  • 2020-12-20 12:14

    You can use the URL object like this:

    const urlWithoutProtocol = new URL(url).host;

    0 讨论(0)
提交回复
热议问题