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, '${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
問題解答
回答1:replace 不會(huì)改變?cè)兄担欠祷匦麓?/p>
其實(shí)你可以用 new RegExp(a, ’g’) 就不需要 eval
相關(guān)文章:
1. docker - 各位電腦上有多少個(gè)容器啊?容器一多,自己都搞混了,咋辦呢?2. java - spring boot 如何打包成asp.net core 那種獨(dú)立應(yīng)用?3. java - 在用戶不登錄的情況下,用戶如何添加保存到購(gòu)物車?4. datetime - Python如何獲取當(dāng)前時(shí)間5. docker start -a dockername 老是卡住,什么情況?6. javascript - nginx反向代理靜態(tài)資源403錯(cuò)誤?7. docker網(wǎng)絡(luò)端口映射,沒有方便點(diǎn)的操作方法么?8. 安全性測(cè)試 - nodejs中如何防m(xù)ySQL注入9. javascript - 關(guān)于apply()與call()的問題10. python - 調(diào)用api輸出頁(yè)面,會(huì)有標(biāo)簽出現(xiàn),請(qǐng)問如何清掉?
