2013-06-18 69 views
0

我想寫一個JavaScript函數,將採取字符串<0>(其中0真的可以是任意數字),在它和刪除它,得到它的數量的實際值。例如,如果它被賦予了這樣一句話:如何獲得Javascript正則表達式匹配的字符串的實際值?

'By now you\'re probably familiar with <0>X, a drawing application that has won an <1>Awards and plenty of attention for its user interface, which has rethought the way basic interactions like <2>pinch-to-zoom or <3>color selection should work on a touchscreen.' 

我希望它給我回這個字符串:

'By now you\'re probably familiar with X, a drawing application that has won an Awards and plenty of attention for its user interface, which has rethought the way basic interactions like pinch-to-zoom or color selection should work on a touchscreen.' 

這陣:

[0, 1, 2, 3] 

目前我有這樣的:

function(sentence) { 
    return sentence.split(/\<[0-9]+\>/).join(''); 
} 

顯然剛剛返回這句話。我需要在標籤內有數字值。有沒有辦法做到這一點?

+2

是否需要糾正獎的拼寫神奇嗎? – Rudu

+0

你希望它去掉'<0>'字符,並返回一個數組*和*這些數字被剝離的句子? –

+0

@Rudu哎呀。大聲笑沒有 – chromedude

回答

2

我建議:

function regexAndArray (str) { 
    var reg = /(<(\d+)>)/g, 
     results = { 
      string : '', 
      stripped : [] 
     }; 
    results.string = str.replace(reg, function(a,b,c){ 
     results.stripped.push(c); 
     return ''; 
    }); 
    return results; 
} 

console.log(regexAndArray('By now you\'re probably familiar with <0>X, a drawing application that has won an <1>Awards and plenty of attention for its user interface, which has rethought the way basic interactions like <2>pinch-to-zoom or <3>color selection should work on a touchscreen.')); 

JS Fiddle demo

參考文獻:

+0

太棒了。謝謝! – chromedude

+0

你真的很受歡迎,很高興得到了幫助。 –

相關問題