2011-11-14 57 views
2

我需要替換從match()獲得的一些數據;如何使用.replace和match()方法javaScript

這包含 「總時間:9分24秒」 一個返回字符串

data.match(/Total time: [0-9]* minutes [0-9]* seconds/); 

,但我只需要 「九分24秒」,我嘗試使用:

data.match(/Total time: [0-9]* minutes [0-9]* seconds/).replace("Total time:", ""); 

但有是錯誤「」

".replace is not a function" 

有人能幫助我嗎?

+0

這看起來非常相似,你剛纔的問題:http://stackoverflow.com/questions/8119585/parsing- string-with-grep。你試圖解決的*實際*問題是什麼? – Johnsyweb

+0

@羅曼,你需要進一步的幫助解決這個問題嗎? –

回答

1
data = 'Total time: 15 minutes 30 seconds'; 
response = data.match(/Total time: [0-9]* minutes [0-9]* seconds/); 
response = response[0]; 
alert(response.replace("Total time:", "")); 
0

JavaScript將返回匹配數組,如果未找到匹配項,則返回null。原始代碼嘗試在數組的實例上調用replace方法,而不是其中的元素(字符串)。

var result = null; 
var m = data.match(/.../); 
if (m) { 
    result = m[0].replace('Total time: ', ''); 
} 
4

使用捕捉你的正則表達式分:

var match = data.match(/Total time: ([0-9]* minutes [0-9]* seconds)/); 
alert(match[1]); 

match()返回一個數組,這就是爲什麼你不能調用replace的結果 - 沒有Array#replace方法。

1

你可以擺脫使用比賽做這樣的事情的......

var match = data.replace(/Total time: ([0-9]* minutes [0-9]* seconds)/,"$1");