[英]Get the current url but without the http:// part bookmarklet!
伙計們,我有一個問題,希望你能幫助我解決這個問題。 我有一個書簽;
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。 對於此網址:
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/
這應該做到這一點
location.href.replace(/https?:\/\//i, "")
使用document.location.host
而不是document.location.href
。 它只包含主機名,而不包含完整的URL。
獲取 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);
你有權控制
website.com
other.example.com嗎? 這可能應該在服務器端完成。
在這種情況下:
preg_replace("/^https?:\/\/(.+)$/i","\\1", $url);
應該管用。 或者,您可以使用str_replace(...)
,但請注意,這可能會從URL中的某處刪除“http://”:
str_replace(array('http://','https://'), '', $url);
編輯:或者,如果你只是想要主機名,你可以試試parse_url(...)
?
使用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等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.