如何使用 JQuery 提取 URL 中的最后一个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1442860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:27:35  来源:igfitidea点击:

how to extract last value in the URL using JQuery

jquery

提问by useranon

how to extract the last value that is 1 from the following Url using jQuery...

如何使用jQuery从以下Url中提取最后一个值为1的值...

Url : /FormBuilder/index.php/reports/export/1

网址:/FormBuilder/index.php/reports/export/1

回答by CMS

You can use substringand lastIndexOf:

您可以使用substringlastIndexOf

var value = url.substring(url.lastIndexOf('/') + 1);

If the second parameter of substringis omitted, it extracts the characters to the end of the string.

如果省略子字符串的第二个参数,则将字符提取到字符串的末尾。

回答by Luke

To get it from the URL Address:

要从 URL 地址获取它:

var value = window.location.href.substring(window.location.href.lastIndexOf('/') + 1);

回答by Carlos

Not really jQUery, but pure Javascript:

不是真正的 jQUEry,而是纯 Javascript:

var a = '/test/foo/bar';

To get the string after the last character:

获取最后一个字符后的字符串:

var result = a.substring(a.lastIndexOf("/") + 1);

回答by nickf

Using a regex, which is just like the lastIndexOfmethod, but with the added benefit of being almost impossible to read/understand! ;)

使用正则表达式,就像lastIndexOf方法一样,但具有几乎无法阅读/理解的额外好处!;)

var lastBit = theUrl.match(/[^\/]*$/)[0];

There actually IS a benefit though, if you only wanted to get trailing numbers, or some other pattern you could adapt it:

不过,实际上有一个好处,如果您只想获得尾随数字或其他一些可以调整它的模式:

// match "/abc/123", not "/abc/foo"
var lastDigits = theUrl.match(/[0-9]*$/)[0];

// match "/abc/Pie", not "/abc/123"
var matches = theUrl.match(/\/(P[^\/]*)$/);
var lastBitWhichStartsWithTheLetterP = matches ? matches[1] : null;

回答by Brian

As you can see from all of the answers JQuery isn't needed to do this.

正如您从所有答案中看到的那样,不需要 JQuery 来执行此操作。

You could split it:

你可以拆分它:

var url = 'www.google.com/dir1/dir2/2';
var id = parseInt(url.split('/')[url.split('/').length - 1]);

回答by kgiannakakis

Why not use a regex?

为什么不使用正则表达式?

var p = /.+\/([^\/]+)/;
var match = p.exec(str)
alert(match[1]);

回答by kgiannakakis

var arr = window.location.split("/FormBuilder/index.php/reports/export/1");
var last_val = arr[arr.length-1];

回答by Webdesign7 London

Universal:

普遍的:

function getQueryVariable(variable)
{
    var pathname = window.location.pathname.split("/");

    for (i = 0; i < pathname.length; i++) {
        if (pathname[i] == variable){
            return pathname[i+1];
        }
    }

}