vIceBerg vIceBerg - 4 months ago 4x
Javascript Question

How to allow user to input escaped chars in Javascript

A simple one here.

I have an HTML in which I want to allow the user to enter escape sequence. Ie:


And I want my script to "interpret" the \n and the \x21 to get:



The purpose of this is to allow the user to enter thermal printer's code in an html page. The printer needs special chars. I want to take that string, "interpret" the special codes and send it to the printer. Currently, the printer prints the string as-is


The only way I can think of that doesn't use a long replace line is with the eval() function. You could, for example, use the following:

function useEscapes(s) {
  return eval('("' + s.replace(/([^\\]|^)(?=(\\\\)*["\n])/g, '$1\\').replace(/\n/g, 'n') + '")');

The replace is to make sure it's safe to pass into the eval() function.