JavaScript >> Javascript 文檔 >  >> Tags >> URL

快速提示:使用 JavaScript 解析 URL 的最簡單方法

我一直最喜歡的 JavaScript 技巧之一是將 URL 解析為不需要任何庫或高級正則表達式的部分(主機、路徑、查詢字符串等)的技術。它只使用 DOM 的力量,更準確地說,是錨元素 <a> .

作為瀏覽器分配給錨元素的常規屬性集的一部分,還有一些模仿 location 的屬性 目的。讓我演示一下:

$(function(){

    // The URL we want to parse
    var url = 'https://tutorialzine.com/2013/07/quick-tip-parse-urls/?key=value#comments';

    // The magic: create a new anchor element, and set the URL as its href attribute.
    // Notice that I am accessing the DOM element inside the jQuery object with [0]:
    var a = $('<a>', { href:url } )[0];

    $('#host').val(a.hostname);
    $('#path').val(a.pathname);
    $('#query').val(a.search);
    $('#hash').val(a.hash);

    // Even more:
    // a.port, a.protocol,
    // a.origin (not available in older IE versions)

});
<ul>
    <li><label for="host">Host:</label> <input type="text" id="host" /></li>
    <li><label for="path">Path:</label> <input type="text" id="path" /></li>
    <li><label for="query">Query String:</label> <input type="text" id="query" /></li>
    <li><label for="hash">Hash:</label> <input type="text" id="hash" /></li>
</ul>
html{
    background-color:#f4f4f4;
    font:14px/1.4 sans-serif;
    color:#666;
}

ul{
    list-style:none;
    width:300px;
    margin:50px auto;
}

li{
    padding:4px;
}

input{
    font:inherit;
    border:1px solid #ccc;
    border-radius:2px;
    padding:2px 5px;
}

label{
    width:90px;
    display:inline-block;
    text-align:right;
}

為了方便起見,我在這裡使用 jQuery,但您可以通過使用 var a = document.createElement('a') 創建錨元素來輕鬆使用純 JavaScript ,然後將 URL 分配給 a.href 直接。

這是另一個更複雜的示例,它可以讓您在文本字段中輸入並實時解析 URL:

$(function(){

    // Cache the fields
    var url = $('#url'), host = $('#host'), path = $('#path'), 
        query = $('#query'), hash = $('#hash');

    // Listen for the input event and update the fields

    url.on('input', function(){
        var a = $('<a>', { href:url.val() } )[0];

        host.val(a.hostname);
        path.val(a.pathname);
        query.val(a.search);
        hash.val(a.hash);
    });

    // Set a default URL 
    url.val('https://tutorialzine.com/2013/07/quick-tip-parse-urls/?key=value#comments');

    // Trigger the input event
    url.trigger('input');
});
<div>
    <label for="url">Enter a URL:</label> <input type="text" id="url" size="50" />
</div>

<ul id="parts">
    <li><label for="host">Host:</label> <input type="text" id="host" /></li>
    <li><label for="path">Path:</label> <input type="text" id="path" /></li>
    <li><label for="query">Query String:</label> <input type="text" id="query" /></li>
    <li><label for="hash">Hash:</label> <input type="text" id="hash" /></li>
</ul>
html{
    background-color:#f4f4f4;
    font:14px/1.4 sans-serif;
    color:#666;
}

ul{
    list-style:none;
    width:300px;
    margin:0 auto;
}

li{
    padding:4px;
}

input{
    font:inherit;
    border:1px solid #ccc;
    border-radius:2px;
    padding:2px 5px;
}

label{
    width:90px;
    display:inline-block;
    text-align:right;
}

div{
    padding:40px;
    text-align:center;
}

這裡唯一的主要區別是我正在監聽 input 事件(舊的 IE 不支持,你必須在那裡使用 keypress),它會在字段值的每次更改時通知事件偵聽器。

以不同的方式設置外部鏈接

該技術的一個有用應用是區別對待外部鏈接。您可以在指向異地的每個鏈接旁邊添加一個圖標,或者您甚至可以顯示某種中間頁面,提醒人們他們正在被重定向到第三方網站。為了檢測外部鏈接,我們將比較 DOM 元素和位置對象的主機名屬性:

$(function(){

    // Get only the external links:
    var external = $('a[href]').filter(function(){
        return this.hostname != location.hostname;
    });

    // In the return above, you may also compare the protocol 
    // property if you wish to distinguish http from https links.

    external.addClass('external');

});
<a href="?page=123">Page 1</a>
<a href="/page2.html">Page 2</a>
<a href="https://demo.tutorialzine.com/">Page 3</a>
<a href="https://tutorialzine.com/page3.html">Page 4</a>
<a href="https://google.com/">Page 5</a>
html{
    background-color:#f4f4f4;
    font:15px/1.4 sans-serif;
    color:#666;
}

body{
    padding:50px;
    text-align:center;
}

a{
    color:#999;
}

a.external{
    color:green;
}

a.external:after{
    content:' ⇲';
}

今天的快速提示到此結束! 我希望你發現這種技術很有用。知道使用 DOM 可以實現的其他很酷的事情嗎?在評論部分分享它們。


下一篇
No
Tutorial JavaScript 教程
  1. 升級到適用於 JavaScript v3 的 AWS 開發工具包

  2. 如何從 Admin Directory 中獲取 Employee Title?

  3. 如何使用 Three.js 和 React 渲染你自己的 3D 模型

  4. 使用 $HOME/.local 保持操作系統清潔

  5. JS 構造函數參數與此:您使用哪個?

  6. 使用 NgIf 和異步管道處理 Observables

  7. 如何使用 Node.js、MongoDB、Fastify 和 Swagger 構建超快的 REST API

  1. 正則表達式備忘單的備忘單,第三部分:POSIX

  2. 在瀏覽器中編輯和上傳文件的問題

  3. 使用 Vue.js 創建電子商務前端 |第 3 部分:願望清單功能

  4. 你應該知道的 7 個乾淨的 JavaScript 代碼技巧

  5. 我的 React 個人頁面

  6. 使用 Node.js 和 OpenTracing 進行微服務分佈式跟踪

  7. 在 JavaScript 中將字符轉換為 ASCII 碼

  1. 使用 Puppeteer 構建 Twitter 圖片下載器

  2. Firefox 44 中的 Web 推送到來

  3. 如何從 The Graph 上的子圖中訪問數據

  4. 我為網站/博客製作了 DEV.to 小部件