首页 > 解决方案 > 凯撒密码 - 空格和其他字符

问题描述

我在下面创建了一个凯撒密码,但我希望返回的字符串包含空格和其他字符。我试过正则表达式,但这似乎并不能解决问题,或者我没有正确使用它,我不太确定。

任何帮助表示赞赏。谢谢!

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

标签: javascriptarraysstringcaesar-cipher

解决方案


RegExp.test返回一个布尔值,String.match返回一个数组。这一行:

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

应该

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

这应该捕获任何不是小写字母(空格、标点符号等)的值 - 如果您也想编码大写,请i在正则表达式的末尾添加标志:/[a-z]/i


推荐阅读