this is the log
JavaScript
x
2
1
console.log(duckShoot(4, 0.64, '|~~2~~~22~2~~22~2~~~~2~~~|'));
2
the output must be====>|~~X~~~X2~2~~22~2~~~~2~~~|
here the code i’ve try:
JavaScript
1
9
1
function duckShoot(ammo, aim, ducks) {
2
3
let shot = Math.floor(ammo * aim)
4
5
// console.log(shot);
6
7
return ducks.replace (/2/g, "X")
8
}
9
how to make /2/g
just replace certain repeating
i wanna make code above same function with this
function duckShoot(ammo, aim, ducks) {
JavaScript
1
12
12
1
let shot = Math.floor(ammo * aim)
2
3
// console.log(shot);
4
5
for (let i = 1; i <= shot; i++) {
6
7
ducks = ducks.replace("2", "X");
8
9
}
10
11
return ducks
12
}
Advertisement
Answer
JavaScript
1
3
1
let c = 2; // how many you want to replace
2
'|~~2~~~22~2~~22~2~~~~2~~~|'.replaceAll('2', o => (c-- >= 0) ? 'X':o )
3
or you can keep the ‘old’ replace with the regex
JavaScript
1
2
1
'|~~2~~~22~2~~22~2~~~~2~~~|'.replace(/2/g, o => (c-- >= 0) ? 'X':o )
2
whereas
JavaScript
1
2
1
(o) => (c-- >= 0) ? 'X':o
2
is a simple function decreasing the counter and returning an ‘X’ or keep the o(riginal)