Skip to content
Advertisement

Javascript Changing inputted word based on function

Expected Output Example: Our word is Pokemon

Pokemon (Regular word)

P!k!m!n (Every 2nd letter is !)

Nomekop (Reversed)

pokemOn (Every 6th letter is uppercase)

[Array of ASCII Values]

I am sure that I have got reverse just fine but need help in figuring out uppercase and changing every 2nd letter and returning ASCII codes of the word.

I would imagine that the logic for replacing is where i%2 = 0 make the character a ‘!’ If uppercase is similar I am struggling to implement it or I could be wrong.

The output looks like this right now

Pokemon undefined Pokemon 80 nomekop

function replaceAt(string) {
  for(let i=0; i=string.length; i++){
    string = word
    string.charAt(i) = '!'
    i++
  }
}

// This function intended to make every 6th letter uppercase
function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  }

function returnASCII(string) {
  for (let i = 0; i < string.length; i++) {
    // How to do this but on one line?
    // Would I have to convert this to an array?
    return string.charCodeAt(i);
  }
}

let word = "Pokemon";
console.log(word)
console.log(replaceAt(1, "!"))
console.log(capitalizeFirstLetter(word));
console.log(returnASCII(word))

// Intended to show word reversed
let reverse = word.split('').reverse().join('').toLowerCase();
console.log(reverse)

I am only concerned with vanilla JS

Any guidance would be greatly appreciated!

Advertisement

Answer

ReplaceAt

For replaceAt, you’re passing two parameters, but you only set up your function with one.

Capitalize Every 6th Letter

To capitalize every 6th letter of a word, do this:

function capitalizeEvery6thLetter(word){
    res = '';
    for(let i = 0; i < word.length; i++){
        if((i % 5) == 0){ // Check i % 5 instead of 6 due to zero indexing
            res += word[i].toUpperCase();
        } else {
          res += word[i]
        }
    }
    return res;
}

Iterate through the word, check if i%5 is 0 (due to every 5th index actually being the 6th letter), set that letter to uppercase and add it to an empty result string, or just add the letter if it i%5 isn’t 0. Then once all the letters are added, return the result.

Word to ASCII Array

For turning a word into an array of ASCII characters, do this:

function asciiValues(word){
  res = [];
  for(let i = 0; i < word.length; i++){
      res.push(word[i].charCodeAt())
  }
  return res;
}

It’s a similar approach to the last function, only get the character code at each letter and add it to an array. In your current function, you have a correct set up, but the return statement of the loop means it only runs once before returning the single letter to ascii.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement