views:

162

answers:

4

Hi!

Guys I have a question, hoping you can help me out with this one. I have a bookmarklet;

javascript:q=(document.location.href);void(open('http://other.example.com/search.php?search='+location.href,'_self ','resizable,location,menubar,toolbar,scrollbars,status'));

which takes URL of the current webpage and search for it in another website. When I use this bookmarklet it takes the whole URL including http:// and searches for it. But now I would like to change this bookmarklet so it will take only the www.example.com or just example.com (without http://) and search for this url. Is it possible to do this and can you please help me with this one?

Thank you!

+1  A: 

This should do it

location.href.replace(/https?:\/\//i, "")
jitter
This works 99% of the time. However it doesn't work if the current Url is e.g. `http://somesite.com/query=http://someothersite.com/blahblah`. All instances of "http://" will be replaced not just the first occurance. Doesn't work for 'https://' too.
o.k.w
Fixed it. Handles http/https + caseinsensitve matching. Also replaces only first occurrence.
jitter
Ok, good effort. +1
o.k.w
A: 

Use document.location.host instead of document.location.href. That contains only the host name and not the full URL.

Gumbo
I am not sure why in the world everyone suggests regular expressions when the location object already does it for you as Gumbo suggested. Documentation is a great thing: https://developer.mozilla.org/En/DOM/Window.location
epascarello
Oh yes, it is easier to use "str = location.host + location.path + location.search". How about port number?
o.k.w
@o.k.w: Bostjan apparently just wants to know the host and not the full URL.
Gumbo
A: 

Do you have control over website.com other.example.com? This should probably be done on the server side.

In which case:

preg_replace("/^https?:\/\/(.+)$/i","\\1", $url);

should work. Or, you could use str_replace(...), but be aware that that might strip 'http://' from somewhere inside the URL:

str_replace(array('http://','https://'), '', $url);

EDIT: or, if you just want the host name, you could try parse_url(...)?

Joe Freeman
A: 

Using javascript replace via regex matching:

javascript:q=(document.location.href.replace(/(https?|file):\/\//,''));void(open('http://website.com/search.php?search='+q,'_self ','resizable,location,menubar,toolbar,scrollbars,status'));

Replace (https?|file) with your choice, e.g. ftp, gopher, telnet etc.

o.k.w
actually this won't work for file as that protocol uses three slashes
jitter
@jitter: "file" wasn't supposed to be included, it has no practical usage. It was added while I was testing the code locally on my machine. Anyway, doesn't really matter :)
o.k.w