2016-11-14 52 views
1

我有一句話,我想只有最後的'和'剩下的,並刪除其他人。刪除除JavaScript以外的特定單詞嗎?

「獅子,老虎和熊,和大象」,我想變成這樣:

「獅子,老虎,熊,和大象」。

我曾嘗試使用正則表達式模式,如str = str.replace(/and([^and]*)$/, '$1');,這顯然沒有奏效。謝謝。

+0

'split'在你想要的單詞中,'join'在除最後一個以外的所有實例中都爲空。 – Marty

+1

http://stackoverflow.com/questions/9694930/remove-all-occurrences-except-last – Marty

回答

4

使用this regex

and (?=.*and) 
  • and比賽任何和後面加一個空格。空間相匹配,以便它在更換去除,以防止有2位
  • (?=.*and)是向前看,這意味着如果隨後.*and,如果後面和

使用此代碼將只匹配:

str = str.replace(/and (?=.*and)/g, ''); 
+0

完美!雖然我用這個'str = str.replace(/ \和(?=。*和)/ g,'');'謝謝。 – sarcastasaur

+0

您的代碼不起作用。你需要使用正則表達式而不是字符串。 – 4castle

1

您可以使用積極的前瞻(?=...),查看當前比賽之前是否有其他and。您還需要使用g製作正則表達式全局。

function removeAllButLastAnd(str) { 
 
    return str.replace(/and\s?(?=.*and)/g, ''); 
 
} 
 

 
console.log(removeAllButLastAnd("Lions, and tigers, and bears, and elephants"));

0
var multipleAnd = "Lions, and tigers, and bears, and elephants"; 
var lastAndIndex = multipleAnd.lastIndexOf(' and'); 
var onlyLastAnd = multipleAnd.substring(0, lastAndIndex).replace(/ and/gi, '')+multipleAnd.substring(lastAndIndex); 
console.log(onlyLastAnd); 
+0

試着解釋你的答案 – Nikhil