javascript - JS using eval to build the replace function is invalid
phpcn_u1582
phpcn_u1582 2017-07-05 10:47:23
0
1
822

Code meaning: Build a simple GADERYPOLUKI decoder

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 

The code is as follows. I want to use the eval function to build a function that can replace characters, but it seems to be useless.

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

phpcn_u1582
phpcn_u1582

reply all(1)
扔个三星炸死你

replace does not change the original value, but returns a new string.

In fact, you can use new RegExp(a, 'g') and there is no need for eval

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!