首頁 > web前端 > js教程 > 主體

如何從沒有正規表示式的 URL 中提取主機名稱根?

DDD
發布: 2024-11-14 21:31:02
原創
673 人瀏覽過

How to Extract Hostname Root from a URL Without Regular Expressions?

Extracting Hostname Root from a URL without Regular Expressions

In the quest to isolate the root of a URL from a text string, there exists a clever technique that bypasses the often criticized performance inefficiencies of regular expressions. This method leverages the hidden capabilities of a simple HTML anchor element.

Solution:

  1. Create an HTML anchor element: .
  2. Set the element's href attribute to the URL in question.
  3. The hostname property of the anchor element will now contain the desired root domain, e.g., "www.example.com".

Example:

To demonstrate, consider the following function:

function url_domain(data) {
  var a = document.createElement('a');
  a.href = data;
  return a.hostname;
}
登入後複製

Using this function, we can extract the domain root from any given URL like so:

url_domain("http://www.example.com/12xy45") // "www.example.com"
url_domain("http://example.com/random") // "example.com"
登入後複製

This method offers a streamlined and efficient solution for extracting hostname roots, circumventing the perceived drawbacks associated with regular expressions in such scenarios.

以上是如何從沒有正規表示式的 URL 中提取主機名稱根?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板