![](/img/trans.png)
[英]How to compare jinja expression in javascript with escape sequences string?
[英]How to honor escape sequences the way String() does
我有一個包含反斜杠轉義序列的字符串,例如:
AB\0C\xff
有沒有一種簡單的解析方法,可以使用與JavaScript字符串解析相同的規則來解釋反斜杠轉義序列,以使上面的代碼生成字節序列:
0x41 0x42 0x00 0x43 0xff
?
我嘗試過String(line)
但是當然沒有效果。
FWIW,這是一個簡短的node.js程序,用於演示我的追求:
'use strict'
const readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
rl.on('line', function(line) {
processLine(line);
});
function hexify(line) {
function hex(v) {
return ((v < 16) ? '0' : '') + v.toString(16);
};
var s=[];
for (var i=0; i<line.length; i++) {
s.push(hex(line.charCodeAt(i)));
};
return s.join(' ');
}
function honorEscapes(line) {
return String(line); // this doesn't do what I want
};
function processLine(line) {
console.log('raw ' + hexify(line));
console.log('parsed ' + hexify(honorEscapes(line)));
};
運行它:
$ node escape.js
AB\0\C\xff
raw 41 42 5c 30 5c 43 5c 78 66 66
parsed 41 42 5c 30 5c 43 5c 78 66 66
您可能正在尋找JSON.parse
,它解析包括轉義字符的JSON字符串 。
當然,這並不包含JavaScript字符串文字中的所有怪異轉義符 。 根據您需要的那些,手動添加它們,例如使用regex:
.replace(/\\0/g, '\u0000')
.replace(/\\x([0-9a-fA-F]{2})/g, function(m, c) { return String.fromCharCode(parseInt(c, 16)); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.