'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 1:[1]
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.
Solution 2:[2]
If anybody landed here looking for the same in Python, use re.escape(str)
Go here for more detailed discussion
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Pointy |
Solution 2 | vinodhraj |