I have the following strings
http://example.com
https://example.com
http://www.example.com
how do i get rid of the http://
or
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.
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);
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 );
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];
Assuming there are no double slashes other than the protocol, you could do:
var url = "https://example.com";
var noProtocol = url.split('//')[1];
You can use the URL object like this:
const urlWithoutProtocol = new URL(url).host;