javascript - JS 利用eval構(gòu)建replace函數(shù)無效
問題描述
代碼含義:構(gòu)建一個簡單的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, '$')`)eval(`str.replace(/${a.toUpperCase()}/g, '${b.toUpperCase()}')`)eval(`str.replace(/$/g, '${a}')`)eval(`str.replace(/${b.toUpperCase()}/g, '${a.toUpperCase()}')`)console.log(a, b, str, `str.replace(/${a}/g, '$')`) } 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
相關(guān)文章:
1. 在應用配置文件 app.php 中找不到’route_check_cache’配置項2. html按鍵開關(guān)如何提交我想需要的值到數(shù)據(jù)庫3. HTML 5輸入框只能輸入漢字、字母、數(shù)字、標點符號?正則如何寫?4. javascript - 請教如何獲取百度貼吧新增的兩個加密參數(shù)5. gvim - 誰有vim里CSS的Indent文件, 能縮進@media里面的6. 跟著課件一模一樣的操作使用tp6,出現(xiàn)了錯誤7. PHP類屬性聲明?8. javascript - JS請求報錯:Unexpected token T in JSON at position 09. objective-c - ios 怎么實現(xiàn)微信聯(lián)系列表 最好是swift10. java - 安卓接入微信登錄,onCreate不會執(zhí)行
