javascript - 我需要一个正则表达式来检查数组的当前索引是否存在于特定的数字范围内
问题描述
我知道这里有很多关于正则表达式的信息,但我似乎真的无法让它发挥作用。我有一个 for 循环,循环遍历一个数组。我想看看数组的当前索引是否不等于一组数字(32-64)。我已经声明了一个变量let patt
,它包含我认为应该工作的正则表达式,但我无法弄清楚检查它的语法。我确信它会是.match
,但再次,不知道如何措辞!.match
任何建议,解决方案,甚至是一个好的 JS 正则表达式教程方向的一点都将不胜感激!
class ShiftCipher{
constructor(shift){
this.shift = shift;
}
encrypt(string){
let up = string.toUpperCase(); //convert string to uppercase
let uni = [];
let newArr = [];
let i, j;
let patt = /[32-64]/g; //think this is wrong...
for(i = 0; i < up.length; i++){
uni.push(up.charCodeAt(i)) //push converted chars as unicodes to new array
if(uni[i] != 32){ // if unicode is 32 (space) leave as is. //I want a regex here for != unicode 32 - 64
uni[i] += this.shift; // shift unicode by parent class specification (shift)
}
}
for(j = 0; j < up.length; j++){
if(uni[j] > 90){ // if unicode is higher than 90(z)..
uni[j] -= 26; // loop back round starting at (a).
}
let text = String.fromCharCode(uni[j]); //convert from unicode to string
newArr.push(text); //push string to array
}
let final = newArr.join(''); //join array elements(as a string) and store in final
console.log(final);
}
}
const cipher = new ShiftCipher(2);
cipher.encrypt('I love to code z!');
解决方案
我想看看数组的当前索引是否不等于一组数字(32-64)
字符代码是数字。尝试数值比较。
for (i = 0; i < up.length; i++) {
if (up.charCodeAt(i) >= 32 && up.charCodeAt(i) <= 64) {
// ...
}
}
但从技术上讲,您也可以使用正则表达式。从字符代码创建字符范围的工作方式如下:
var patt = /[\x20-\x40]/; // hex 20 = decimal 32, hex 40 == decimal 64
for (i = 0; i < up.length; i++) {
if (patt.test(up.charAt(i)) {
// ...
}
}
请注意,这使用.charAt()
.
被/[\x20-\x40]/
解释为好像您已经编写了实际字符,因此在这种情况下它相当于/[ -@]/
.
推荐阅读
- flutter - 如何使用 Unicode 在飞镖中打印符号?
- typescript - 检查字符串文字联合类型打字稿中是否存在字符串
- spring-boot - Kotlin 中将数据对象保存在另一个数据对象中的最佳实践问题
- c# - asp.net core 5 mvc 超级管理员连接
- java - 操作栏上的后退按钮
- python - 如何根据特定列对相关矩阵进行排名?
- block - 以编程方式显示块工具栏
- php - Wordpress/Woocommerce:如何在自定义位置显示“我的帐户”不同部分的内容?
- c# - 使用因属性而异的元素反序列化 XML
- java - 我需要使用一些开源 Java 库或程序将 PDF 转换为 PDF/A。有可能实现这一目标吗?