[英]Matching the last digit or digits after a forward slash
In a JavaScript function in my Rails app, I'm trying to get the id of a recipe. 在我的Rails应用程序的JavaScript函数中,我正在尝试获取配方的ID。 Looking inside the event object like this 查看这样的事件对象
e.delegateTarget.baseURI
produces the uri, the last number of which (after the forward slash) is the id I want. 产生uri,其中最后一个数字(在正斜杠之后)是我想要的id。
http://myroute.com/users/2/recipes/6
Of course, that id could be much longer in the future, so I need to be able to get all the digits after the last forward slash. 当然,将来这个id可能要长得多,所以我需要能够在最后一个正斜杠之后得到所有数字。
I tried to get the last id this way 我试着用这种方式获得最后一个id
var uri = e.delegateTarget.baseURI
var re = /^(.*[\\\/\d])/;
var recipe_id = uri.match(re);
The matched slash is supposed to be the last one because .* matches greedily, and then I look for any digit. 匹配的斜杠应该是最后一个因为。*匹配贪婪,然后我寻找任何数字。 This is all wrong. 这都错了。 I'm not very experienced with regular expressions. 我对正则表达式不太熟悉。 Can you help? 你能帮我吗?
A very simple way to do this would be to use string.split() 一个非常简单的方法是使用string.split()
var uri = "http://myroute.com/users/2/recipes/6",
splituri = uri.split('/');
recipe_id = splituri[splituri.length - 1] // access the last index
Edit: 编辑:
Even easier with the .pop() method, which returns the popped value 使用.pop()方法更容易,它返回弹出的值
like elclanrs said. 像elclanrs说的那样。
var uri = e.delegateTarget.baseURI,
recipe_id = uri.split('/').pop();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.