skip to Main Content

Given a string change the every second letter to an uppercase ‘Z’. Assume there are no space.

let string be javascript

Example output: jZvZsZrZpZ OR each letter on a new line

HERE IS MY CODE

let newarr = str1.split(''); 
let newword = "Z";
for(i = 1; i < newarr.lenth; i += 2){
newarr[i] = newword; newword.join('');}
 
console.log(newword);

Here is my other code I tried

let newarr = str1.split(''); 
for(i = 1; i < newarr.lenth; i+=2){
newarr.replace('newarr[i]' , 'z'); newarr.join('');}
 
console.log(newarr);

Which code closer to correct ? And where Did I go wrong for both codes??

2

Answers


  1. To summarize the things that went wrong:

    1. Split is not needed, you can just access string with their index as well. (as long you want letter per letter)
    2. Same goes for .join(”). It’s redudant if you just create a string from another string
    3. You use replace(‘newarr[i]’…), the first parameter is a string here and will not find what you want, drop the quotes to pass the value inside newarr

    I made a simple approach. Keep in mind this is not the most optimal because I unnecessary loop unchanged letters, which you have done better:

    // You need a new string from another string,
    // No need to create arrays
    let originalString = 'ThisIsTheTestString'
    let newString = ''
    
    // Loop every letter, this is not the most optimal, but (to me) the most understandable
    for (index in originalString) {
    
      // If index is divisable by two, add a Z
      if ((parseInt(index) + 1) % 2 === 0) {
        newString += 'Z'
      } else {
      // Else we are just going to add the original letter
        newString += originalString[index]
      }
    }
    
    // Show result
    console.log(newString)

    With a more optimal loop:

    // You need a new string from another string,
    // No need to create arrays
    let originalString = 'ThisIsTheTestString'
    let newString = originalString
    
    for (var i = 1; i < originalString.length; i = i + 2) {
      // You can't mutate a string directly so a fix could be this:
      newString = newString.substring(0, i) + 'Z' + newString.substring(i + 1);
    }
    // Show result
    console.log(newString)
    Login or Signup to reply.
  2. You could do it with a Regular Expression:

    const str = "javascript";
    const result = str.replace(/(.)./gm, "$1Z");
    console.log('Result:',result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search