JavaScript >> Javascript 文檔 >  >> Tags >> split

parseUri:在 JavaScript 中拆分 URL

更新: 以下帖子已過時。請參閱 parseUri 1.2 獲取最新、最棒的版本。

為了好玩,我花了 10 分鐘將我的 parseUri() ColdFusion UDF 轉換為 JavaScript 函數。

還沒看過的朋友,我再重複一下我在另一篇文章中的解釋……

parseUri() 將任何格式正確的 URI 拆分為其部分(都是可選的 )。請注意,所有部分都使用反向引用通過單個正則表達式進行拆分,並且所有不包含完整 URI 部分的分組都是非捕獲的。這個函數我最喜歡的一點是它對拆分目錄路徑和文件名的強大支持(它支持帶有句點的目錄,並且沒有尾隨反斜杠),我在其他 URI 解析器中沒有看到匹配。由於函數返回一個對象,你可以這樣做,例如,parseUri(uri).anchor 等。

我應該注意到,按照設計,這個函數不會嘗試驗證它接收到的 URI,因為這會限制它的靈活性。 IMO,驗證是一個完全不相關的過程,應該在將 URI 拆分為各個部分之前或之後進行。

這個函數沒有依賴關係,應該可以跨瀏覽器工作。它已在 IE 5.5–7、Firefox 2 和 Opera 9 中進行了測試。

/* parseUri JS v0.1.1, by Steven Levithan <http://stevenlevithan.com>
Splits any well-formed URI into the following parts (all are optional):
----------------------
- source (since the exec method returns the entire match as key 0, we might as well use it)
- protocol (i.e., scheme)
- authority (includes both the domain and port)
  - domain (i.e., host; can be an IP address)
  - port
- path (includes both the directory path and filename)
  - directoryPath (supports directories with periods, and without a trailing backslash)
  - fileName
- query (does not include the leading question mark)
- anchor (i.e., fragment) */
function parseUri(sourceUri){
	var uriPartNames = ["source","protocol","authority","domain","port","path","directoryPath","fileName","query","anchor"],
		uriParts = new RegExp("^(?:([^:/?#.]+):)?(?://)?(([^:/?#]*)(?::(\\d*))?)((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[\\?#]|$)))*/?)?([^?#/]*))?(?:\\?([^#]*))?(?:#(.*))?").exec(sourceUri),
		uri = {};
	
	for(var i = 0; i < 10; i++){
		uri[uriPartNames[i]] = (uriParts[i] ? uriParts[i] : "");
	}
	
	/* Always end directoryPath with a trailing backslash if a path was present in the source URI
	Note that a trailing backslash is NOT automatically inserted within or appended to the "path" key */
	if(uri.directoryPath.length > 0){
		uri.directoryPath = uri.directoryPath.replace(/\/?$/, "/");
	}
	
	return uri;
}

測試一下。

有沒有更精簡、更簡陋的 URI 解析器? 🙂

編輯: 此函數當前不支持包含用戶名或用戶名/密碼對的 URI(例如,“http://user:[email protected]/”)。當我最初編寫基於此的 ColdFusion UDF 時,我並不關心這一點,因為我從不使用這樣的 URI。然而,自從我發布了這個,我覺得應該有支持。支持這樣的 URI 並適當地拆分部分會很容易。需要更長的時間是建立一個適當的、大量的各種 URI 列表(包括格式正確的和不正確的)來重新測試函數。但是,如果有人發表評論尋求支持,我會繼續添加。


Tutorial JavaScript 教程
  1. 如何使用 JavaScript 獲取屬性的值

  2. 讓我們構建我們的第一個 JavaScript npm 包!

  3. 2021 年 Javascript 函數終極參考

  4. 如何使用 javascript 獲取 div 的值

  5. 狀態機出現:一個事件,兩種可能的狀態轉換 (15/24)

  6. React Native for Web – 一次編寫,隨處運行

  7. React 開發人員的可訪問性

  1. Kafka 與 RabbitMQ:比較 Node.js 消息代理

  2. 如何在 VanillaJS 中使用環境變量

  3. 25 個帶有酷炫動畫的創意 404 錯誤頁面

  4. 使用 Cloudflare 頁面為 Angular 應用程序託管您的 Kendo UI

  5. 功能性思維

  6. 如何將 Google 表格中的數據複製為 HTML 表格

  7. 尋找JS導師!

  1. 帶有 XState 和 Styled System 的有狀態樣式

  2. 瀏覽器控制台的完整指南

  3. 如何:使用 Live Reload 在 PHP 應用程序中嵌入 Svelte 應用程序

  4. 將 Strapi 作為無頭 CMS 添加到 11ty 博客