簡體   English   中英

在字符串javascript中刪除n次出現的感嘆號

[英]remove n occurrences of exclamation marks in a string javascript

我想知道是否有人知道如何在字符串中替換n次出現的感嘆號。 我需要從左到右刪除句子中的n驚嘆號, n總是正整數。

一個例子如下:

remove("Hi!!!",1) === "Hi!!"
remove("!!!Hi !!hi!!! !hi",3) === "Hi !!hi!!! !hi"

我嘗試了很多方法,但到目前為止還沒有運氣。 這是我最近的嘗試。

function remove(str, n){
   str.replace(/!{n}/g, '');
}

想法:匹配/替換所有感嘆號,但在替換函數中檢查n並有條件地返回空字符串(刪除! )或原始字符串(保持! )。

另外,每次減少n ! 被什么都沒有取代。

 function remove(str, n) { return str.replace(/!/g, function (m0) { if (n > 0) { n--; return ''; } return m0; }); } console.log(remove("Hi!!!",1)); console.log(remove("!!!Hi !!hi!!! !hi",3)); 

如果n高於數量,此算法將刪除所有感嘆號! 在輸入字符串中。

您可以使用.replace()replacer函數來僅替換第一個項目數,直到num的傳遞值:

 const remove = function(str, n) { let i = 0; const res = str.replace(/!/g, match => i++ < n ? '' : match); // if i is smaller than the num, replace it with nothing (ie remove it) else, when i becomes greater, leave the current matched item in the string and don't remove it return res; } console.log(remove("Hi!!!", 1)); // === "Hi!!" console.log(remove("!!!Hi !!hi!!! !hi", 3)) // === "Hi !!hi!!! !hi" 

或者,如果你願意,一個單行:

 const remove = (str, n) => str.replace(/!/g, match => n --> 0 ? '' : match); // Results: console.log(remove("Hi!!!", 1)); // === "Hi!!" console.log(remove("!!!Hi !!hi!!! !hi", 3)) // === "Hi !!hi!!! !hi" 

您可以將計數作為計數器並檢查它是否達到零。 如果沒有減少並用空字符串替換,否則用找到的字符串替換。

 const remove = (s, n) => s.replace(/\\!/g, _ => n && n-- ? '' : _); console.log(remove("Hi!!!", 1) === "Hi!!"); console.log(remove("!!!Hi !!hi!!! !hi", 3) === "Hi !!hi!!! !hi"); 

暫無
暫無

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

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