获取当前网址但没有http://部分书签!

时间:2009-11-08 13:15:27

标签: javascript url bookmarklet host

伙计我有一个问题,希望你能帮我解决这个问题。我有一个书签;

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

获取当前网页的网址并在其他网站中搜索。当我使用这个书签时,它会获取包括http://在内的整个网址并进行搜索。但是现在我想更改这个书签,这样只需要www.example.comexample.com(没有http://)并搜索此网址。是否可以这样做,你可以帮我解决这个问题吗?

谢谢!

5 个答案:

答案 0 :(得分:20)

JavaScript可以部分访问当前的URL。对于此网址:

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

window.location.protocol = "http"

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

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

请检查:http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/

答案 1 :(得分:9)

这应该这样做

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

答案 2 :(得分:3)

使用document.location.host代替document.location.href。它只包含主机名而不是完整的URL。

答案 3 :(得分:-1)

您是否可以控制 website.com other.example.com?这应该可以在服务器端完成。

在哪种情况下:

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

应该有效。或者,您可以使用str_replace(...),但请注意,这可能会从网址中的某处删除“http://”:

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

编辑:或者,如果您只想要主机名,可以尝试parse_url(...)

答案 4 :(得分:-1)

通过正则表达式匹配使用javascript replace

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

用您的选择替换(https?|文件),例如ftp,gopher,telnet等。