代码含义:构建一个简单的GADERYPOLUKI解码器
The GADERYPOLUKI is a simple substitution cypher used in scouting to encrypt messages. The encryption is based on short, easy to remember key. The key is written as paired letters, which are in the cipher simple replacement.
example:
encode("ABCD", "agedyropulik"); // => GBCE
代码如下,我想用eval函数构建出可以替换字符的函数,但是貌似没有用。
function decode(str,key) {
key = key.split('')
while (key.length>0) {
let b = key.pop(), a = key.pop();
eval(`str.replace(/${a}/g, "${b}")`)
eval(`str.replace(/${a.toUpperCase()}/g, "${b.toUpperCase()}")`)
eval(`str.replace(/${b}/g, "${a}")`)
eval(`str.replace(/${b.toUpperCase()}/g, "${a.toUpperCase()}")`)
console.log(a, b, str, `str.replace(/${a}/g, "${b}")`)
}
return str
}
console.log(decode("Hmdr nge brres", "gaderypoluki"))
console.log("Hmdr nge brres".replace(/g/g, "a"))
>>> k i Hmdr nge brres str.replace(/k/g, "i")
l u Hmdr nge brres str.replace(/l/g, "u")
p o Hmdr nge brres str.replace(/p/g, "o")
r y Hmdr nge brres str.replace(/r/g, "y")
d e Hmdr nge brres str.replace(/d/g, "e")
g a Hmdr nge brres str.replace(/g/g, "a")
Hmdr nge brres
Hmdr nae brres
replace 不会改变原有值,而是返回新串。
其实你可以用
new RegExp(a, 'g')
就不需要 eval