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. python - (初學者)代碼運行不起來,求指導,謝謝!2. 為什么python中實例檢查推薦使用isinstance而不是type?3. mysql里的大表用mycat做水平拆分,是不是要先手動分好,再配置mycat4. window下mysql中文亂碼怎么解決??5. sass - gem install compass 使用淘寶 Ruby 安裝失敗,出現 4046. html5 - H5 SSE的本質是什么?7. javascript - h5上的手機號默認沒有識別8. python - 獲取到的數據生成新的mysql表9. python的文件讀寫問題?10. javascript - js 對中文進行MD5加密和python結果不一樣。
