代碼含義:構(gòu)建一個(gè)簡(jiǎn)單的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函數(shù)構(gòu)建出可以替換字符的函數(shù),但是貌似沒(méi)有用。
function decode(str,key) {
key = key.split('')
while (key.length>0) {
let b = key.pop(), a = key.pop();
eval(`str.replace(/${a}/g, "$")`)
eval(`str.replace(/${a.toUpperCase()}/g, "${b.toUpperCase()}")`)
eval(`str.replace(/$/g, "${a}")`)
eval(`str.replace(/${b.toUpperCase()}/g, "${a.toUpperCase()}")`)
console.log(a, b, str, `str.replace(/${a}/g, "$")`)
}
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 不會(huì)改變?cè)兄?,而是返回新串?/p>
其實(shí)你可以用 new RegExp(a, 'g')
就不需要 eval