javascript - JS 利用eval構建replace函數無效
問題描述
代碼含義:構建一個簡單的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函數構建出可以替換字符的函數,但是貌似沒有用。
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 不會改變原有值,而是返回新串。
其實你可以用 new RegExp(a, ’g’) 就不需要 eval
相關文章:
1. javascript - npm下載的模塊不完整是什么問題?2. java - Spring事務回滾問題3. mysql 聯表查詢4. apache - 想把之前寫的單機版 windows 軟件改成網絡版,讓每個用戶可以注冊并登錄。類似 qq 的登陸,怎么架設服務器呢?5. node.js - 我想讓最后進入數據庫的數據,在前臺最先展示,如何做到?6. MySQL數據庫服務器循環插入執行速度慢7. 剛放到服務器的項目出現這中錯誤,有高手指點嗎8. wordpress - Nginx中禁止訪問txt,robots.txt文件例外,規則該怎么寫?9. python 操作mysql如何經量防止自己的程序在之后被惡意注入(說白了就是問一下python防注入的一些要點)10. mysql - 面試題:如何把login_log表轉換成last_login表?
