0

hello everyone please i'am a begginer in javascript and i found this challenge , but i don't know how to solve it

let str1 = "javascript";  

// Example output: 
// jZvZsZrZpZ OR each letter on a new line
// HINT: You can use  if((i+1) % 2 == 0) to check for even indexes 

for (let i = 0; i < str1.length; i++) {
if ((i + 1) % 2 === 0) {
    str1[i].replace(str1[i],"z")
}
}

can you explain this for me please i try this soltuion but it doesn't work

medtaza
  • 3
  • 1
  • 1
    strings are immutable so you cannot directly replace a character at an index. you may have to do something like https://stackoverflow.com/a/1431109/13583510 – cmgchess Feb 28 '22 at 14:28
  • or you can make str1 into an array by [...str1] then you can directly change elements in the array inside loop. and finally join the array to get back string – cmgchess Feb 28 '22 at 14:30

2 Answers2

0

This should work for you. JsFidle

let str1 = "javascript";  

const res = [...str1].map((letter, index)=>{
 return index % 2 != 0 ? "Z" : letter
})

console.log(res.join(""))
OndrejHj04
  • 320
  • 2
  • 12
0

let str1 = "javascript";  
// Example output: 
// jZvZsZrZpZ OR each letter on a new line
var a = str1.split("");
let replaceChar = function(char){
for(let i=1;i<str1.length;i++){
    if((i+1)% 2 === 0)
     a[i] = char
    }
 return a.join("");
}
console.log( replaceChar("Z"))