简体   繁体   中英

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:

0x41 0x42 0x00 0x43 0xff

?

I tried String(line) but of course that had no effect.

FWIW, here's a short node.js program to demonstrate what I'm after:

'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.

Of course that does not encompass all the weird escapes in JavaScript string literals . Depending on which of those you do need, add them manually for example using regex:

.replace(/\\0/g, '\u0000')
.replace(/\\x([0-9a-fA-F]{2})/g, function(m, c) { return String.fromCharCode(parseInt(c, 16)); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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