0

I am creating a cipher that takes a string and changes each letter to move forward 3 spaces. For instance "Hello!" would turn into "Khoor!", but I have hit a snag. When people type in something that isn't a letter, like a "!" or a space in between letters, I want to be able to just return that value. So a "!" would stay a "!" and a space would stay a space. I want to create an if statement inside of a loop to accomplish this, but how do I differentiate between letters and non-letters?

Attached is my loop, and I want to be able to put in an if statement so it would read "if input is non-letter, then return input. If input is a letter then move forward 3 spaces."

var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var string = "Hello World!"
var stringArr = string.split("")
var codedLet = [];

for (var i = 0; i < string.length; i++) {
  var input = stringArr[i].toLowerCase()
  var codedNum = alphabet.indexOf(input) + 3
  codedLet[i] = alphabet[codedNum]
}
Ryan
  • 151
  • 11
  • 1
    you could use a simple regex to determine if the character is between the range of A-Z or a-z. – Devin Fields Jun 26 '18 at 17:20
  • 1
    Possible duplicate of [javascript regex : only english letters allowed](https://stackoverflow.com/questions/3073176/javascript-regex-only-english-letters-allowed) – StudioTime Jun 26 '18 at 17:20
  • 2
    There are multiple ways to check if a string is a number in JavaScript, and I'd imagine that all of them are pretty well documented here on StackOverflow if you were to search. Consider doing some more research and making some attempts of your own, and then coming here with specific examples of what _isn't_ working if you can't figure it out. – Tyler Roper Jun 26 '18 at 17:21
  • 1
    Possible duplicate of [Regex to match only letters](https://stackoverflow.com/questions/3617797/regex-to-match-only-letters) – Devin Fields Jun 26 '18 at 17:23
  • 1
    Why don't you use ASCII codes instead of your alphabet array? That would definitely cover more symbols. – Hirasawa Yui Jun 26 '18 at 17:24

2 Answers2

0

There are two ways :

One would be to use regex of the type [a-zA-Z]{1} or you can try something like

if(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
ManavM
  • 2,918
  • 2
  • 20
  • 33
0

If you need a cipher which shifts symbols, why not to shift all of them?

See the snippet below:

let string = "Hello World!"

const cipher = (s) => [...s].reduce(
(a, l) => a + String.fromCodePoint(l.codePointAt() + 3), '')

const decipher = (s) => [...s].reduce(
(a, l) => a + String.fromCodePoint(l.codePointAt() - 3), '')

let cs = cipher(string)

console.log(cs)
console.log(decipher(cs))
Kosh
  • 16,966
  • 2
  • 19
  • 34