Search code examples
javascriptregexescaping

How to dynamically add escape character for any character in javascript?


I have got p element with some text. In this text in HTML code I use some "escape" characters like \n, \?, \t, etc. When I get the string in JS code, it is treated as \\n, \\?, \\t. I want to replace it for REAL escaped characters as below in the snippet.

I want to change all "\\char" from the string into output escaped "\char".

It works when I replace all the characters separately (as below), but I wonder how to do that once for all characters preceded by \ in my text.

I need something like this:

.replace(/\\/,'\')

or something like this:

.replace(/\\(.)/,'\$1')

but it does not work because the slash \ makes the following sign ' or $ escaped in the code. Is there any way to insert escape character other than use \ ?

var input = document.getElementById('sampInput');
var output = document.getElementById('sampOutput');

var parsedInput = input.innerHTML
                   .replace(/\\n/g,'\n')
                   .replace(/\\t/g,'\t')
                   .replace(/\\\*/g,'*')
                   .replace(/\\\?/g,'?');

output.innerHTML = parsedInput;
p {
  white-space:pre;
}
<h4>Input:</h4>
<p id="sampInput">hello\nworld\nhello\tworld\nsome \? character and another \* character</p>

<h4>Output:</h4>
<p id="sampOutput"></p>


Solution

  • There's no direct way to do what you're asking, but you can write some code to do it:

    var charmap = {
      n: "\n",
      r: "\r",
      f: "\f",
      t: "\t",
      b: "\b"
    };
    var replaced = string.replace(/\\(.)/g, function(_, char) {
      return (char in charmap) ? charmap[char] : char;
    });
    

    If you wanted to additionally parse \uNNNN escapes, that'd be a little more complicated.