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. Docker for Mac 創建的dnsmasq容器連不上/不工作的問題2. html5 - 為什么有的時候要在網頁中加偽元素3. html - Python2 BeautifulSoup 提取網頁中的表格數據及連接4. python - PyCharm里的一個文件不小心忽略了wx包5. html5 - css 這種六邊形的邊框怎么畫?6. html5 - javascript讀取自定義屬性的值,有的能夠取到,有的取不到怎么回事??7. 小白學python的問題 關于%d和%s的區別8. win10 Apache24+PHP8.0,Apache不能正常加載php.ini。9. javascript - 關于微信掃一掃的技術問題10. html5 - 請問利用font-face定義的字體怎么在canvas里應用?
