URL最后一部分正则表达式

时间:2018-03-10 10:26:22

标签: javascript regex

我需要在最后用html获取我的URL的最后一部分。因此,如果我有此网址http://step/build/index.html,我只需要index.html。我需要用javascript

来做这件事
let address = http://step/build/index.html;
let result = address.match(/html/i);

我试过这个,但它对我不起作用,也许我犯了一些错误。 How do I get the last segment of URL using regular expressions 有人可以帮我解释一下吗? 谢谢。

4 个答案:

答案 0 :(得分:3)

您可以在斜杠上拆分它,然后获取最后一项:



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




答案 1 :(得分:3)

您可以使用此.html RegEx。

提取/[^/]+\.html/i文件名部分

请参阅下面的代码。

const regex = /[^/]+\.html/i;

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

同样的RegEx也会匹配文件名,因为URL有其他参数。

const regex = /[^/]+\.html/i;

let address = "http://step/build/index.html?name=value";
let result = address.match(regex);
console.log(result);

答案 2 :(得分:1)

您可以使用split返回一个数组以在正斜杠上拆分,然后使用pop从数组中删除最后一个元素并返回:



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




如果您有查询字符串参数,例如可以从?#开始,您可以再次使用拆分并从数组中获取第一项:



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




答案 3 :(得分:1)

这是一种非正则表达方法。在工作中应该更可靠/更合适,具体取决于您是否需要其他特定于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);




相关问题