views:

68

answers:

3

I have the following strings

http://site.com
https://site.com
http://www.site.com

how do i get rid of the http:// or https:// in javascript or jquery

+4  A: 
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];
Bick
works great but what about if the string might or might not have http:// some already come in with the format as site.com and on those it fails
Matt
If there is no "http/https":
Bick
var txt="https://site.com";txt=/((http(s)?:\/\/)?(.+)$/i.exec(txt);txt=txt[3];
Bick
`txt=/(?:https?:\/\/)?(.*)$/i.exec(txt)[1];` No need to capture http or https, using * instead of + so that a string with only https?:// will return an empty string.
some
+2  A: 
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 );
patrick dw
@patrick dw, I think you got the wrong language there. :P
Jacob Relkin
I like this one, very simple, and no need for a regex. @Jacob looks like perfectly valid javascript to me?
Mads Jensen
will turn "site.com" into "te.com" though...idx = str.indexOf(':')if(idx >= 0){ str = str.substr(idx + 3);}
Mike Ruhlin
If you want to parse both situations (with http/without) you must use regex, or repeat regex engine work, and make it yourself using string functions. Which is better?
Bick
@Bick - See my update.
patrick dw
+4  A: 

Try with this:

var url = "https://site.com";
var urlNoProtocol = url.replace(/^https?\:\/\//i, "");
ncardeli
"http" forgotten
Bick
It works both with http and https. The "s" character is optional.
ncardeli
@ncardeli: I really like how clean this code is. I can't see why your second regexp is necessary... The first one removes the http/https protocol if it is present. If it isn't present there is nothing to replace and the string is returned as is.
some
You are right, don't know what I was thinking. I'll edit my answer.
ncardeli