简体   繁体   English

URL最后一部分正则表达式

[英]URL last part regular expression

I need to get the last part of my URL with html on the end. 我需要使用html末尾获取URL的最后一部分。 So if I have this url http://step/build/index.html I need to get only index.html . 因此,如果我拥有此URL http://step/build/index.html ,则只需获取index.html I need to do this with javascript 我需要使用javascript

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

I tried this, but it doesn't work for me, maybe I make some mistakes. 我试过了,但是对我来说不起作用,也许我犯了一些错误。 How do I get the last segment of URL using regular expressions Could someone help me and explain it in details? 如何使用正则表达式获取URL的最后一段,有人可以帮我详细解释一下吗? Thank you. 谢谢。

You could split it on slashes and then fetch the last item: 您可以将其分割为斜杠,然后获取最后一项:

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

You can extract the .html filename part using this /[^/]+\\.html/i RegEx. 您可以使用此/[^/]+\\.html/i RegEx提取.html文件名部分。

See the code below. 请参见下面的代码。

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

The same RegEx will also match the filename incase the URL has additional parameters. 如果URL具有其他参数,则同一个RegEx也将匹配文件名。

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

You could use split which returns an array to split on a forward slash and then use pop which removes the last element from the array and returns that: 您可以使用split返回数组以正斜杠分割,然后使用pop从数组中删除最后一个元素并返回:

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

If you have querystring parameters which could for example start with ? 如果您有querystring参数,例如,可以以?开头? or # , you might use split again and get the first item from the array: # ,您可能会再次使用split并从数组中获取第一项:

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

Here's a non-regex approach. 这是一种非正则表达式的方法。 Should be more reliable/appropriate at the job, depending on whether you'll need other URL-specific parts: 根据您是否需要其他特定于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