taking off the http or https off a javascript string

前端 未结 12 1601
面向向阳花
面向向阳花 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: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 );
    

提交回复
热议问题