2016-11-14 53 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