Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to replace some character with certain repeting regex

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

}

>Solution :

You can use something like below, where n is the number of occurrences. For n=2, it will replace the first 2 and so on as you call

n = 2;
newTxt = txt.replace(/2/g, s => n && n-- && 'X' || s);

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~~~|'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading