[英]Matching the last digit or digits after a forward slash
在我的Rails應用程序的JavaScript函數中,我正在嘗試獲取配方的ID。 查看這樣的事件對象
e.delegateTarget.baseURI
產生uri,其中最后一個數字(在正斜杠之后)是我想要的id。
http://myroute.com/users/2/recipes/6
當然,將來這個id可能要長得多,所以我需要能夠在最后一個正斜杠之后得到所有數字。
我試着用這種方式獲得最后一個id
var uri = e.delegateTarget.baseURI
var re = /^(.*[\\\/\d])/;
var recipe_id = uri.match(re);
匹配的斜杠應該是最后一個因為。*匹配貪婪,然后我尋找任何數字。 這都錯了。 我對正則表達式不太熟悉。 你能幫我嗎?
一個非常簡單的方法是使用string.split()
var uri = "http://myroute.com/users/2/recipes/6",
splituri = uri.split('/');
recipe_id = splituri[splituri.length - 1] // access the last index
編輯:
使用.pop()方法更容易,它返回彈出的值
像elclanrs說的那樣。
var uri = e.delegateTarget.baseURI,
recipe_id = uri.split('/').pop();
你應該使用特殊字符$
,這意味着輸入結束:
re = /\d+$/; //matches one or more digits from the end of the input
這是JavaScript正則表達式的一個很好的資源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.