简体   繁体   English

如何从Url客户端获取ID?

[英]How to get an Id out of a Url client side?

If I have a URl like "/api/User/Details/2c021192-25cb-43e1-9bba-3bd5604a0a3d" what would be the best way to get the ID "2c02ds92-25cb-43e1-9bba-3bd5604a0a3d" out of the URL client side? 如果我有一个类似于"/api/User/Details/2c021192-25cb-43e1-9bba-3bd5604a0a3d" "2c02ds92-25cb-43e1-9bba-3bd5604a0a3d"从URL客户端获取ID "2c02ds92-25cb-43e1-9bba-3bd5604a0a3d"的最佳方式是什么?侧?

I need to be able to build a $.getJSON request with the ID and I'm looking for the cleanest way to do it using JavaScript, jQuery, etc. Thanks 我需要能够使用ID构建$.getJSON请求,我正在寻找使用JavaScript,jQuery等最干净的方法。谢谢

$.getJSON('/api/User/2c021192-25cb-43e1-9bba-3bd5604a0a3d')...

Use regular expressions and extract the appropriate part (which seems to be UUID) from the URL. 使用正则表达式并从URL中提取适当的部分(似乎是UUID)。

The alternative is to just split the string by / and get last element. 另一种方法是将字符串拆分为/并获取最后一个元素。

EDIT : The example on how to retrieve UUID from the URI: 编辑 :如何从URI中检索UUID的示例:

var url = '/api/User/2c021192-25cb-43e1-9bba-3bd5604a0a3d';

var pattern = /[\da-f]{8}\-[\da-f]{4}\-[\da-f]{4}\-[\da-f]{4}\-[\da-f]{12}/;
var match = url.match(pattern)[0];

url.match(pattern) returns array of matches, so assuming there is at least one, and only one match, you should pick it (using [0] , as in the example). url.match(pattern)返回匹配数组,因此假设至少有一个且只有一个匹配,则应该选择它(使用[0] ,如示例中所示)。

Proof: http://jsfiddle.net/p6zud/2/ 证明: http//jsfiddle.net/p6zud/2/

EDIT 2 : Shortened the pattern used for matching (see revision history for comparison). 编辑2 :缩短用于匹配的模式(参见修订历史记录以进行比较)。

If the id is always going to be the last section of the URI, you could do something like 如果id总是将成为URI的最后一部分,那么你可以做类似的事情

var url_array = document.location.split('/');
var id = url_array[url_array.length - 1];

using split , convert the url to an array of parameters. 使用split ,将url转换为参数数组。 Then last array item in your case would be your ID. 然后你的案例中的最后一个数组项将是你的ID。

there are very sophisticated URL parsers out there for javascript, perhaps you should look around on google for one that suits your needs. 有非常复杂的URL解析器用于javascript,也许你应该在谷歌上寻找一个适合你的需求。

尝试这个

alert("/api/User/Details/2c021192-25cb-43e1-9bba-3bd5604a0a3d".split('/').slice(-1)[0]);

The simpliest: 最简单的:

var id = '/api/User/2c021192-25cb-43e1-9bba-3bd5604a0a3d'.split('/User/')[1];

Gives you 2c021192-25cb-43e1-9bba-3bd5604a0a3d ; 给你2c021192-25cb-43e1-9bba-3bd5604a0a3d ;

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

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