簡體   English   中英

URL最后一部分正則表達式

[英]URL last part regular expression

我需要使用html末尾獲取URL的最后一部分。 因此,如果我擁有此URL http://step/build/index.html ,則只需獲取index.html 我需要使用javascript

let address = http://step/build/index.html;
let result = address.match(/html/i);

我試過了,但是對我來說不起作用,也許我犯了一些錯誤。 如何使用正則表達式獲取URL的最后一段,有人可以幫我詳細解釋一下嗎? 謝謝。

您可以將其分割為斜杠,然后獲取最后一項:

 let address = "http://step/build/index.html"; let result = address.split("/").pop(); console.log(result) 

您可以使用此/[^/]+\\.html/i RegEx提取.html文件名部分。

請參見下面的代碼。

 const regex = /[^/]+\\.html/i; let address = "http://step/build/index.html"; let result = address.match(regex); console.log(result); 

如果URL具有其他參數,則同一個RegEx也將匹配文件名。

 const regex = /[^/]+\\.html/i; let address = "http://step/build/index.html?name=value"; let result = address.match(regex); console.log(result); 

您可以使用split返回數組以正斜杠分割,然后使用pop從數組中刪除最后一個元素並返回:

 let address = "http://step/build/index.html".split('/').pop(); console.log(address); 

如果您有querystring參數,例如,可以以?開頭? # ,您可能會再次使用split並從數組中獲取第一項:

 let address2 = "\\"http://step/build/index.html?id=1&cat=2" .split('/') .pop() .split(/[?#]/)[0]; console.log(address2); 

這是一種非正則表達式的方法。 根據您是否需要其他特定於URL的部分,工作應該更可靠/更合適:

 // Note the ?foo=bar part, that URL.pathname will ignore below let address = 'http://step/build/index.html?foo=bar'; let url = new URL(address); // Last part of the path console.log(url.pathname.split('/').pop()); // Query string console.log(url.search); // Whole data console.log(url); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM