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>

3
  • 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. Commented Jan 3, 2017 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 Commented Jan 3, 2017 at 16:41
  • Pawle, "some\*text\?sample" = "some*text?sample", that string literal of yours contains no literal backslashes. Commented Jan 3, 2017 at 16:49

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.