this is the log
console.log(duckShoot(4, 0.64, '|~~2~~~22~2~~22~2~~~~2~~~|'));
the output must be====>|~~X~~~X2~2~~22~2~~~~2~~~|
here the code i've try:
function duckShoot(ammo, aim, ducks) {
let shot = Math.floor(ammo * aim)
// console.log(shot);
return ducks.replace (/2/g, "X")
}
how to make /2/g
just replace certain repeating
i wanna make code above same function with this
function duckShoot(ammo, aim, ducks) {
let shot = Math.floor(ammo * aim)
// console.log(shot);
for (let i = 1; i <= shot; i ) {
ducks = ducks.replace("2", "X");
}
return ducks
}
CodePudding user response:
You can use replacerFunction
argument in .replace()
. Here shot is the number of occurrences.
return ducks.replace(/2/g, s => shot && shot-- && 'X' || s);
Explanantion:
.replace(regexp, replacerFunction) can have a replacerFunction
as the second argument and we have made use of it. The function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.
replacerFunction
: I have just iterated the replace function until the shot
becomes 0. logical AND (&&)
returns false if one of the opearnds are false, and shot--
will decrement the value each iteration until it becomes 0. Since true && 'X'
is X
, it will replace. 0 is a false condition and will break the loop and return the current replaced string.
So your function will look like this below
function duckShoot(ammo, aim, ducks) {
let shot = Math.floor(ammo * aim)
return ducks.replace(/2/g, s => shot && shot-- && 'X' || s);
}
console.log(duckShoot(4, 0.64, '|~~2~~~22~2~~22~2~~~~2~~~|'))
//|~~X~~~X2~2~~22~2~~~~2~~~|
CodePudding user response:
let c = 2; // how many you want to replace
'|~~2~~~22~2~~22~2~~~~2~~~|'.replaceAll('2', o => (c-- >= 0) ? 'X':o )
or you can keep the 'old' replace with the regex
'|~~2~~~22~2~~22~2~~~~2~~~|'.replace(/2/g, o => (c-- >= 0) ? 'X':o )
whereas
(o) => (c-- >= 0) ? 'X':o
is a simple function decreasing the counter and returning an 'X' or keep the o(riginal)