【问题标题】:Get the current url but without the http:// part bookmarklet!获取当前 url 但没有 http:// 部分小书签!
【发布时间】:2022-01-12 19:12:13
【问题描述】:

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

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

获取当前网页的 URL 并在另一个网站中搜索它。当我使用这个小书签时,它会获取包括http:// 在内的整个 URL 并搜索它。但现在我想更改这个书签,所以它只需要www.example.com 或只需要example.com(没有http://)并搜索这个url。是否可以这样做,您能帮我解决这个问题吗?

谢谢!

【问题讨论】:

    标签: javascript url bookmarklet host


    【解决方案1】:

    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/

    【讨论】:

    • 谢谢,简单明了:)
    【解决方案2】:

    应该这样做

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

    【讨论】:

    • 这在 99% 的时间里都有效。但是,如果当前 URL 是例如它不起作用http://somesite.com/query=http://someothersite.com/blahblah。 “http://”的所有实例都将被替换,而不仅仅是第一次出现。也不适用于“https://”。
    • 已修复。处理 http/https + caseinsensitive 匹配。也只替换第一次出现。
    【解决方案3】:

    使用document.location.host 而不是document.location.href。这仅包含主机名,而不包含完整的 URL。

    【讨论】:

    • 我不知道为什么世界上每个人都建议正则表达式,而 location 对象已经按照 Gumbo 的建议为你做了。文档是个好东西:developer.mozilla.org/En/DOM/Window.location
    • 哦,是的,使用“str = location.host + location.path + location.search”更容易。端口号呢?
    • @o.k.w:Bostjan 显然只是想知道主机而不是完整的 URL。
    【解决方案4】:

    使用 URL api

    获取部分 URL 的现代方法是从给定的 url 创建一个 URL 对象。

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

    您当然可以将窗口位置或任何其他 url 作为参数传递给 URL 构造函数。

    这样

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

    【讨论】:

      【解决方案5】:

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

      在这种情况下:

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

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

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

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

      【讨论】:

      • 这是一个 JavaScript 问题;这些是 PHP 函数。
      【解决方案6】:

      通过正则表达式匹配使用 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?|file) 替换为您的选择,例如ftp、gopher、telnet等

      【讨论】:

      • 实际上这不适用于文件,因为该协议使用三个斜杠
      • @jitter: "file" 不应该包含在内,它没有实际用途。它是在我在我的机器上本地测试代码时添加的。无论如何,这并不重要:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-02
      • 1970-01-01
      • 1970-01-01
      • 2011-07-31
      • 1970-01-01
      • 2011-10-24
      相关资源
      最近更新 更多