Вы можете использовать функцию replacer в .replace()
для замены только первого числа элементов до переданного значения 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"