简体   繁体   中英

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. 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.

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.

I tried to get the last id this way

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()

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

like elclanrs said.

var uri = e.delegateTarget.baseURI,
    recipe_id = uri.split('/').pop();

You should use the special character $ , which means end of input:

re = /\d+$/; //matches one or more digits from the end of the input

Here is a good resource on JavaScript regular expressions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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