javascript - JS 利用eval構(gòu)建replace函數(shù)無效
問題描述
代碼含義:構(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ù),但是貌似沒有用。
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
問題解答
回答1:replace 不會(huì)改變?cè)兄?,而是返回新串?/p>
其實(shí)你可以用 new RegExp(a, ’g’) 就不需要 eval
相關(guān)文章:
1. javascript - 能否讓vue-cli的express修改express重啟服務(wù)2. 解決Android webview設(shè)置cookie和cookie丟失的問題3. javascript - gulp打包引入文件路徑在生產(chǎn)環(huán)境和開發(fā)環(huán)境下的切換4. node.js - npm一直提示proxy有問題5. python - 我想把下面代碼中的多余空白行去除該怎么做,如何用正則實(shí)現(xiàn)6. PHP單例模式7. 最新版本的微信web開發(fā)者工具必須要APPID,會(huì)提供測(cè)試號(hào),但是像你一樣tabBar配置的話不會(huì)顯示首頁與日志,難道我要下載跟你一樣的版本?8. 網(wǎng)頁爬蟲 - python爬蟲翻頁問題,請(qǐng)問各位大神我這段代碼怎樣翻頁,還有價(jià)格要登陸后才能看到,應(yīng)該怎么解決9. python - tweepy 庫 連接Twitter API 報(bào)錯(cuò)10. python - 網(wǎng)頁title中包含換行,如何用正則表達(dá)式提取出來?
