2010-03-15 111 views
0
var exampleURL = '/example/url/345234/test/'; 
var numbersOnly = [?] 

/url//test部分路徑將始終相同。從JavaScript使用JavaScript提取數字?

請注意,我需要/url//test之間的數字。在上面的示例網址中,佔位符詞示例可能不時是數字,但在這種情況下,它不應該匹配。只有/url//test之間的數字。

謝謝!

回答

6
var exampleURL = '/example/url/345234/test/'; 

// this will remove all non-numbers 
var numbers = exampleURL.replace(/[\D]/g, ''); 

// or you can split the string and take only that 3rd bit 
var numbers = exampleURL.split(/\//)[3]; 

// or match with a regex 
var numbers = exampleURL.match(/\/(\d+)\/test\//)[1]; 
1

正則表達式,將工作是

matches = exampleURL.match('/\/.+\/url/([0-9]+)\/test\//'); 

,我認爲這是正確的。

4

這些方針的東西:

var result; 
result = value.match(/\/url\/([0-9]+)\/test/); 
// use result[1] to get the numbers (the first capture group) 

這依賴於/url//test位,因爲你說他們是可靠的。更一般地,這將匹配數字的第一運行在字符串中

var result; 
result = value.match(/[0-9]+/); 
// use result[0] (not result[1]), which is the total match 

MDC page on regular expressions是非常有用的。

注意:可以使用\d代替「digit」,而不是上面的[0-9]。我不是因爲我的正則表達式虛弱而且我永遠不會記得它(當我這樣做時,我永遠不會記住它是全部數字還是全部非數字[這是\D - 你看到我的困惑]。我發現[0-9]後來看得很清楚,其他人可能會發現\d更清晰,但對於我來說,我喜歡列出範圍的明確性