Jake
Jake

Reputation: 149

Caesar Cipher - spaces and other characters

I have created a Caesar Cipher code below but I want the returned string to include spaces and other characters. I've tried regex but this does not seem to solve the problem or maybe i'm not using it right, I'm not too sure.

Any help appreciated. Thanks!

function caesarCipher(str, n) {
  let newStr = '';
  let alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('')
  let regex = /[a-z]/

  for (let i = 0; i < str.length; i++) {
    if (str[i].match(regex) === false) {
      newStr += str[i]
      continue;
    }
    let currentIndex = alphabet.indexOf(str[i]);
    let newIndex = currentIndex + n;
    newStr += alphabet[newIndex];
  }
  return newStr
}

console.log(caesarCipher('ebiil tloia!', 3)) //should return hello world! but returns hellocworldc

Upvotes: 1

Views: 665

Answers (2)

helloitsjoe
helloitsjoe

Reputation: 6529

RegExp.test returns a boolean, String.match returns an array. This line:

if (str[i].match(regex) === false) {

should be

if (regex.test(str[i]) === false) {

This should catch any value that's not a lowercase letter (spaces, punctuation, etc) - If you want to encode uppercase too, add the i flag at the end of the regex: /[a-z]/i

Upvotes: 2

Jack Bashford
Jack Bashford

Reputation: 44135

Firstly, you need to pass the shift (3) to the function. Secondly, since there are no spaces in alphabet, you need to add a test:

function caesarCipher(str, n) {
  let newStr = '';
  let alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('')
  let regex = /[a-z]/

  for (let i = 0; i < str.length; i++) {
    if (str[i].match(regex) === false) {
      newStr += str[i]
    }
    let currentIndex = alphabet.indexOf(str[i]);
    if (!(currentIndex + 1)) {
      newStr += " ";
    } else {
      let newIndex = currentIndex + n;
      newStr += alphabet[newIndex];
    }
  }
  return newStr
}

console.log(caesarCipher('ebiil tloia!', 3)) //should return hello world! but returns hellocworldc

Upvotes: 0

Related Questions