简体   繁体   English

在字符串javascript中删除n次出现的感叹号

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

I am wondering if anyone knows how to replace n number of occurrences of exclamation marks in a string. 我想知道是否有人知道如何在字符串中替换n次出现的感叹号。 I need to remove n exclamation marks in the sentence from left to right and n is always positive integer. 我需要从左到右删除句子中的n惊叹号, n总是正整数。

An example would be as follows: 一个例子如下:

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

I have tried many approaches but have had no luck so far. 我尝试了很多方法,但到目前为止还没有运气。 Here is my latest attempt. 这是我最近的尝试。

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

Idea: Match/replace all exclamation marks, but check n in the replacement function and conditionally return either an empty string (remove ! ) or the original string (keep ! ). 想法:匹配/替换所有感叹号,但在替换函数中检查n并有条件地返回空字符串(删除! )或原始字符串(保持! )。

Also, decrement n each time a ! 另外,每次减少n ! is replaced by nothing. 被什么都没有取代。

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

This algorithm removes all exclamation marks if n is higher than the number of ! 如果n高于数量,此算法将删除所有感叹号! in the input string. 在输入字符串中。

You can use the replacer function in .replace() to replace only the first number of items upto the passed value of num : 您可以使用.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" 

Or, if you like, a one-liner: 或者,如果你愿意,一个单行:

 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" 

You could take the count as counter and check ich it reaches zero. 您可以将计数作为计数器并检查它是否达到零。 if not decrement and replace with an empty string, otherwise replace with the found string. 如果没有减少并用空字符串替换,否则用找到的字符串替换。

 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