简体   繁体   English

如何像String()那样遵循转义序列

[英]How to honor escape sequences the way String() does

I have a string that contains backslashed escape sequences, such as: 我有一个包含反斜杠转义序列的字符串,例如:

AB\0C\xff

Is there a simple way to parse that that interprets backslashed escape sequences using the same rules as JavaScript string parsing such that the above would generate the byte sequence: 有没有一种简单的解析方法,可以使用与JavaScript字符串解析相同的规则来解释反斜杠转义序列,以使上面的代码生成字节序列:

0x41 0x42 0x00 0x43 0xff

?

I tried String(line) but of course that had no effect. 我尝试过String(line)但是当然没有效果。

FWIW, here's a short node.js program to demonstrate what I'm after: 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)));
};

Running it: 运行它:

$ 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

You might be looking for JSON.parse , which parses JSON strings including escaped characters. 您可能正在寻找JSON.parse ,它解析包括转义字符的JSON字符串

Of course that does not encompass all the weird escapes in JavaScript string literals . 当然,这并不包含JavaScript字符串文字中的所有怪异转义 Depending on which of those you do need, add them manually for example using regex: 根据您需要的那些,手动添加它们,例如使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM