程式碼意義:建立一個簡單的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 假 inj.
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