I've been trying decode text, so I can take unescape JSON encoding. But I can't get to work when the variable value is innerHTML but it works when I hardcode the same string value to the variable.
innerHTML Example (I need help with)
<html>
<body>
<p id="uri">C:\\Users\\User\\Documents\\Fax</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var uri = document.getElementById("uri").innerText;
var dec = decodeURI(uri.toString());
var res = "Decoded URI: " + dec;
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
Expected Result: Decoded URI: C:\Users\User\Documents\Fax
Working example with a hardcoded value
<html>
<body>
<p id="uri">Decode</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var uri = "C:\\Users\\User\\Documents\\Fax";
var dec = decodeURI(uri.toString());
var res = "Decoded URI: " + dec;
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
Actual Result: Decoded URI: C:\Users\User\Documents\Fax
What am I doing wrong?
The line:
actually sets
uri
toC:\Users\User\Documents\Fax
. Since you are simply creating a string with the backslashes escaped.The line:
sets
uri
toC:\\Users\\User\\Documents\\Fax
with two backslashes in each position.If you want the string solution to behave the same, you need to escape the backslashes again when creating the string. (i.e.
var uri = "C:\\\\Users\\\\User\\\\Documents\\\\Fax";
)To fix your first version to work as the second currently does, you can use a RegEx replacement to change
C:\\Users\\User\\Documents\\Fax
toC:\Users\User\Documents\Fax
(or if it is possible, simply change the html element to containC:\Users\User\Documents\Fax
).RegEx solution:
To parse all escaped characters (
\\
,\n
,\r
,\t
, ...):