javascript - 凯撒密码 - 空格和其他字符
问题描述
我在下面创建了一个凯撒密码,但我希望返回的字符串包含空格和其他字符。我试过正则表达式,但这似乎并不能解决问题,或者我没有正确使用它,我不太确定。
任何帮助表示赞赏。谢谢!
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
解决方案
RegExp.test
返回一个布尔值,String.match
返回一个数组。这一行:
if (str[i].match(regex) === false) {
应该
if (regex.test(str[i]) === false) {
这应该捕获任何不是小写字母(空格、标点符号等)的值 - 如果您也想编码大写,请i
在正则表达式的末尾添加标志:/[a-z]/i
推荐阅读
- php - Github.com 无法呈现换行符
- c# - MS Project C# 以编程方式添加预算
- vba - 子或函数未定义 MS Access SendEmailFromOutlook
- python - AWS Python 开发工具包 - 发送 CLI 命令
- node.js - 在 Node 中保存来自 REST POST 调用的数据
- sql - 用于获取 5 列相同但只有一列不同的所有记录的 sql 查询
- r - 嵌套数据框上的函数向量算术
- ruby-on-rails - 设计:如何在更新用户信息时跳过电子邮件验证?
- acumatica - Acumatica - 由于图像而设置网格行高
- php - 您指定的 PHP exe 文件未正确运行:C:\xampp\php\php.exe 。我已附加我的 php.ini 文件我应该更改什么