1

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>
Paweł
  • 4,238
  • 4
  • 21
  • 40
  • What do you expect `\*` or `\?` to mean? Like, what Unicode code point do you want that to be? They're not standard JavaScript escape codes like `\t` and `\n`. – Pointy Jan 03 '17 at 16:36
  • Yes I know. I just want to get the same effect as you get with any escaped character in your JS string `console.log("some\*text\?sample"); \\some*text?sample` – Paweł Jan 03 '17 at 16:41
  • Pawle, `"some\*text\?sample"` = `"some*text?sample"`, that string literal of yours contains no literal backslashes. – Wiktor Stribiżew Jan 03 '17 at 16:49

2 Answers2

3

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
0

If anybody landed here looking for the same in Python, use re.escape(str) Go here for more detailed discussion

vinodhraj
  • 177
  • 1
  • 7