Click here to Skip to main content
15,887,966 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
JavaScript
function bs(str){
  //storage for new string
  let newStr = '';
  //storage for character codes
  let arr = [];
  
  //loop to cycle through each letter in the string then return it into the array
  for(let i = 0; i < str.length; i++){
    let charCode = str.charCodeAt(i) + 1;
    
    //if char is z or Z loop back around to the approppriate a or A
    (str[i] == 'z') ? arr.push(97):
    (str[i] == 'Z') ? arr.push(65):
    arr.push(charCode);
    
    //if the input is not a letter then return the text below
    return (charCode > 123) ? "Letters only, please" :
    (charCode <= 64) ? "Letters only, please" :
    (charCode <= 96 && charCode > 91) ? "Lettes only, please" : undefined;
    
     }
  //decipher each char code in the array then return it to a string
    newStr = arr.map( n => String.fromCharCode(n)).join('') 
  
    return newStr
}

console.log(bs("Z"))


What I have tried:

In this code I am trying to replace every character in a given string with the character following it in the alphabet. However I only want letters to be returned. My code was working fine before I tried to filter out non letters. Now when I enter letters I get undefined as my return. How do I fix this?
Posted
Updated 15-May-23 3:52am

1 solution

Bear in mind that characters sets are reasonable sensible: 'a' is less than 'b', which is less that 'c', and so on up to 'z'. And the same applies for the uppercase letters as well: 'A' < 'B' < 'C' ... < 'Z'
So, you can write a conditional that filters to just lowercase alphabetic characters like this:
JavaScript
if (charCode >= 'a' && charCode <='z')


Then ... it gets nasty. Javascript is a weakly (or poorly if you prefer) typed language - which means in this case that the type of variable changes depending on what you do with it.
So adding on to a character doesn't return a character - it returns a pair of characters: "x" + 1 == "x1" as the addition is assumed to be string concatenation. That why your code uses charCodeAt rather than charAt - but you need to convert it back when you try to build a string using string.fromCharCode:
JavaScript
let result = "";
str = "12Hello34";
for(let i = 0; i < str.length; i++) {
    let charCode = str.charCodeAt(i);
    if (charCode >= 65 && charCode <= 90 ) {
       if (charCode == 90) charCode = 65;
       else charCode = charCode + 1;
       }
    else if (charCode >= 97 && charCode <= 122 ) {
       if (charCode == 122) charCode = 97;
       else charCode = charCode + 1;
       }
    result += String.fromCharCode(charCode);
    }
console.log (result);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900