Bostjan
Bostjan

Reputation: 161

Get the current url but without the http:// part bookmarklet!

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!

Upvotes: 16

Views: 30798

Answers (5)

Joe Lloyd
Joe Lloyd

Reputation: 22323

Use the URL api

A modern way to get a part of the URL can be to make a URL object from the url that you are given.

const { hostname } = new URL('https://www.some-site.com/test'); // www.some-site.com 

You can of course just pass window location or any other url as an argument to the URL constructor.

Like this

const { hostname } = new URL(document.location.href);

Upvotes: 1

AHMED RABEE
AHMED RABEE

Reputation: 481

JavaScript can access the current URL in parts. For this URL:

http://css-tricks.com/example/index.html

window.location.protocol = "http"

window.location.host = "css-tricks.com"

window.location.pathname = "/example/index.html"

please check: http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/

Upvotes: 33

jitter
jitter

Reputation: 54605

This should do it

location.href.replace(/https?:\/\//i, "")

Upvotes: 14

o.k.w
o.k.w

Reputation: 25790

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.

Upvotes: -1

Gumbo
Gumbo

Reputation: 655129

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

Upvotes: 4

Related Questions