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

Replace each nth character with "_"

I’m trying to solve a coding problem and it seems my thinking process is wrong in this problem. I’m trying to solve the following:

/*
        Given a string and a number n, replace every nth character with '_'.
        "foreigner", 2 => "f_r_i_n_r"
        "leetcode", 3 => "le_tc_de"
        "leetcode", 1 => "________"
        */
function replaceChar(string1, number) {
  let stringArr = string1.split("")
  for (let i = 0; i < stringArr.length; i++) {
    if (i === i + 1) {
      stringArr[i] = "_"
    }
  }
  stringArr.join('')
  console.log(stringArr)
}
replaceChar("foreigner", 2);

The function at bottom is written by me and it seems it’s not working as I intended.

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

>Solution :

You got the funcion almost right, except for the if (i === i + 1) condition…

You need to check if the remainder of (i + 1 / number) is 0:

function replaceChar(string1, number) {
  let stringArr = string1.split("")
  for (let i = 0; i < stringArr.length; i++) {
    if ((i + 1) % number === 0) {
      stringArr[i] = "_"
    }
  }
  console.log(stringArr)
  // or: return stringArr.join('')?

}
replaceChar("foreigner", 2);

BTW As other pointed out, the stringArr.join('') is not doing anything – you probably need to assign it to a variable and return it (or return it directly – as proposed in the code).

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