簡體   English   中英

刪除JavaScript中除last以外的特定單詞?

[英]Remove specific words except last in JavaScript?

我有一句話,我只想保留最后一個“和”,並刪除其他的。

“獅子,老虎,熊和大象”,我想將其轉換為:

“獅子,老虎,熊和大象”。

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

使用此正則表達式

and (?=.*and)
  • and匹配任意一個,后跟一個空格。 空格匹配,因此在替換時將其刪除,以防止有2個空格
  • (?=.*and)是超前的,這意味着僅當其后跟.*and時才匹配.*and

使用此代碼:

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

您可以使用正前瞻(?=...)看看是否有另一個and超前的電流匹配。 您還需要使用g使正則表達式全局。

 function removeAllButLastAnd(str) { return str.replace(/and\\s?(?=.*and)/g, ''); } console.log(removeAllButLastAnd("Lions, and tigers, and bears, and elephants")); 

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM