簡體   English   中英

如何替換 JavaScript 中除第一個之外的所有字符串?

[英]How to replace all occurrences of a string except the first one in JavaScript?

我有這個字符串:

hello world hello world hello world hello

我需要得到以下信息:

hello world hello hello hello

如果我使用:

str = str.replace('world', '');

它只刪除上面字符串中第一次出現的world

除了第一個之外,我如何替換它的所有出現?

您可以將函數傳遞給String#replace ,您可以在其中指定省略替換第一次出現的內容。 還要使您的第一個參數替換正則表達式以匹配所有出現的內容。

演示

 let str = 'hello world hello world hello world hello', i = 0; str = str.replace(/world/g, m => !i++ ? m : ''); console.log(str);

筆記

您可以通過使用IIFE來避免使用全局計數器變量i

 let str = 'hello world hello world hello world hello'; str = str.replace(/world/g, (i => m => !i++ ? m : '')(0)); console.log(str);

為了提供@Kristianmitk 優秀答案的替代方案,我們可以使用正向后視,它在Node.Js和 Chrome >= 62 中受支持

 const string = 'hello world hello world hello world hello'; console.log( string.replace(/(?<=world[\\s\\S]+)world/g, '') ); // or console.log( string.replace(/(?<=(world)[\\s\\S]+)\\1/g, '') );


使用Symbol.replace眾所周知的符號。

Symbol.replace 眾所周知的符號指定替換字符串的匹配子字符串的方法。 該函數由 String.prototype.replace() 方法調用。

 const string = 'hello world hello world hello world hello'; class ReplaceButFirst { constructor(word, replace = '') { this.count = 0; this.replace = replace; this.pattern = new RegExp(word, 'g'); } [Symbol.replace](str) { return str.replace(this.pattern, m => !this.count++ ? m : this.replace); } } console.log( string.replace(new ReplaceButFirst('world')) );

在我的解決方案中,我用當前時間戳替換第一次出現,然后替換所有出現,最后用world替換時間戳

您也可以使用str.split('world')然后加入

var str = 'hello world hello world hello world hello';
var strs = str.split('world');
str = strs[0] + 'world' + strs.slice(1).join('');
console.log(str);

 var str = 'hello world hello world hello world hello'; const d = Date.now() str = str.replace('world', d).replace(/world/gi, '').replace(d, 'world'); console.log(str);

 var str = 'hello world hello world hello world hello'; var count = 0; var result = str.replace(/world/gi, function (x) { if(count == 0) { count++; return x; } else { return ''; } }); console.log(result);

我會這樣做:

  1. 獲取子字符串直到並包括第一次出現。
  2. 在第一次出現后附加子字符串,並刪除所有其他出現:

 function replaceExceptFirst(str, search) { let index = str.indexOf(search); return str.substring(0, index + search.length) + str.substring(index + search.length).replace(/world/g, '') } console.log(replaceExceptFirst('hello world hello world world hello', 'world'))

暫無
暫無

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

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