[英]How to unescape JavaScript string literal value?
I am using regex to parse javascript code (using an ES parser, such as Esprima, is not an option for technical environment limitations). 我正在使用正则表达式来解析javascript代码(使用ES解析器,例如Esprima,不是技术环境限制的选项)。
The subject code (the code being parsed is): 主题代码(正在解析的代码是):
(function() {
$('#3bf779cd').replaceWith("<div class=\'shows\'>\n<\/div>");
window.fadeItems();
}).call(this);
The value I am interested in is the first parameter of replaceWith
, which is a string literal. 我感兴趣的值是replaceWith
的第一个参数,它是一个字符串文字。 I am getting this variable using regex: 我使用正则表达式获取此变量:
const subjectValue = subjectCode.match(/\.replaceWith\(((["'])(?:(?=(\\?))\3.)*?\2)/m)[1].slice(1, -1);
console.log(subjectValue);
The output of this is: 这个输出是:
<div class=\'shows\'>\n<\/div>
How do I escape subjectValue
in a way that the output would be: 如何以输出的方式转义subjectValue
:
<div class='shows'>
</div>
Simply using unescape
has no effect. 简单地使用unescape
没有任何效果。
If I am not mistaken, the question comes does to how to unescape this value: 如果我没有弄错的话,问题就在于如何摆脱这个价值:
console.log('"<div class=\\\'shows\\\'>\\\\n<\\\/div>"');
You're looking for eval
(yes you heard correctly): 你正在寻找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>
The most idiotic way would be. 最愚蠢的方式是。
"<div class=\\'shows\\'>\\\\n<\\/div>".replace(/\\n/g, '').replace(/\\/g, '');
// "<div class='shows'></div>"
Smarter way would be to first unescape \\n's than check with regex if there are unescaped matches, and than escape those as well. 如果有未转义的比赛,那么更聪明的方法就是先用正则表达式进行检查,而不是逃避它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.