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. html5 - 在一個頁面中 初始了兩個swiper 不知道哪里錯了 一直不對2. html5和Flash對抗是什么情況?3. mac連接阿里云docker集群,已經卡了2天了,求問?4. docker綁定了nginx端口 外部訪問不到5. 前端 - 微信支付開發:調用jsapi時缺少參數total_fee6. 微信小程序session無法緩存的問題7. mysql錯誤,求mysql大神8. java - 關于aop在controller不起用的問題9. phpadmin的數據庫,可以設置自動變化時間的變量嗎?就是不需要接收時間數據,自動變化10. vue.js - nginx反向代理location順序問題
