简体   繁体   中英

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. I need to remove n exclamation marks in the sentence from left to right and n is always positive integer.

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 ! ).

Also, decrement n each time a ! 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 ! 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM