简体   繁体   English

提取URL末尾字符之间的字符串

[英]Extract string between characters at the end of a URL

I have the following example url: http://example.com/this/is/the/end/ 我有以下示例网址: http://example.com/this/is/the/end/ : http://example.com/this/is/the/end/

I need to extract the last piece of the url, between the last two / 我需要提取网址的最后一部分,在最后两个/之间

There may be characters after the last / but it's always between the last two / that I need. 在最后一个/后面可能会有一些字符,但是它总是在我需要的最后两个/之间。

This is what I'm trying, I think it's pretty close but it only returns the d of end 这是我正在尝试的方法,我认为它非常接近,但只返回endd

How can I extract the full end ? 如何提取完整的结尾

Javascript Java脚本

var str = 'http://example.com/this/is/the/end/';

var string = str.substring(str.lastIndexOf("/")-1,str.lastIndexOf("/"));

Here's a fiddle 这是一个小提琴

Use lastIndexOf with start from index as second parameter to extract the text between the two slashes. lastIndexOfindex一起用作第二个参数,以提取两个斜杠之间的文本。

 var str = 'http://example.com/this/is/the/end/'; var lastIndex = str.lastIndexOf('/'); var string = str.substring(str.lastIndexOf("/", lastIndex - 1) + 1, lastIndex); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ : Get the last `/` index by starting search from `lastIndex - 1` index. console.log(string); 


You can also use string and array functions as follow. 您还可以如下使用字符串和数组函数。

 var str = 'http://example.com/this/is/the/end/'; var string = str.split('/').slice(-2)[0]; console.log(string); 


Also, regex can be used. 另外,可以使用正则表达式。

Regex Demo and Explanation 正则表达式演示和说明

 var str = 'http://example.com/this/is/the/end/'; var string = str.match(/\\/(\\w+)\\/[^\\/]*?$/)[1]; console.log(string); 

This is a good place to use regular expressions: 这是使用正则表达式的好地方:

Regex Live Demo 正则表达式现场演示

var str = 'http://example.com/this/is/the/end/';
var re = /\/([^\/]*)\/[^\/]*$/;
//        \/  - look for /
//          ([^\/]*) - capture zero or more characters that aren't a /
//                  \/ - look for last /
//                    [^\/]* - look for more chars that aren't /
//                          $ - match the end of the string
var last = re.exec(str)[1];
console.log(last); //end

您可以简单地拆分和切片

'http://example.com/this/is/the/end/'.split('/').slice(-2)[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM