簡體   English   中英

如何unescape JavaScript字符串文字值?

[英]How to unescape JavaScript string literal value?

我正在使用來解析代碼(使用ES解析器,例如Esprima,不是技術環境限制的選項)。

主題代碼(正在解析的代碼是):

(function() {
    $('#3bf779cd').replaceWith("<div class=\'shows\'>\n<\/div>");

    window.fadeItems();
}).call(this);

我感興趣的值是replaceWith的第一個參數,它是一個字符串文字。 我使用正則表達式獲取此變量:

const subjectValue = subjectCode.match(/\.replaceWith\(((["'])(?:(?=(\\?))\3.)*?\2)/m)[1].slice(1, -1);

console.log(subjectValue);

這個輸出是:

<div class=\'shows\'>\n<\/div>

如何以輸出的方式轉義subjectValue

<div class='shows'>
</div>

簡單地使用unescape沒有任何效果。

如果我沒有弄錯的話,問題就在於如何擺脫這個價值:

console.log('"<div class=\\\'shows\\\'>\\\\n<\\\/div>"');

你正在尋找eval (是的,你聽錯了):

 text = document.querySelector('script').textContent; dqString = /"(\\\\.|[^"])*"/g s = text.match(dqString)[0] raw = eval(s); alert(raw); 
 <script> (function() { $('#3bf779cd').replaceWith("<div class=\\'shows\\'>\\n<\\/div>"); window.fadeItems(); }); </script> 

最愚蠢的方式是。

"<div class=\\'shows\\'>\\\\n<\\/div>".replace(/\\n/g, '').replace(/\\/g, '');
// "<div class='shows'></div>"

如果有未轉義的比賽,那么更聰明的方法就是先用正則表達式進行檢查,而不是逃避它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM