Escaping Strings in JavaScript
http://locutus.io/php/strings/addslashes/
function addslashes( str ) {
return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}
React escapes already escaped string
Just send plain unescaped strings from back-end.
It should be front-end who decides how to render and whether to escape the data, and unless you use dangerouslySetInnerHTML
you are safe.
Let's say somebody has written a comment containing xss script. You can save the comment in a database as is, and then React will automatically escape it for you, so that script will never be evaluated (again, unless you use dangerouslySetInnerHTML
to render the comment).
Javascript - How to show escape characters in a string?
If your goal is to have
str = "Hello\nWorld";
and output what it contains in string literal form, you can use JSON.stringify
:
console.log(JSON.stringify(str)); // ""Hello\nWorld""
const str = "Hello\nWorld";
const json = JSON.stringify(str);
console.log(json); // ""Hello\nWorld""
for (let i = 0; i < json.length; ++i) {
console.log(`${i}: ${json.charAt(i)} (0x${json.charCodeAt(i).toString(16).toUpperCase().padStart(4, "0")})`);
}
.as-console-wrapper {
max-height: 100% !important;
}
Alternatives to escape(string) in JavaScript
In EcmaScript spec there is algorithm:
- Call ToString(string).
- Compute the number of characters in Result(1).
- Let R be the empty string.
- Let k be 0.
- If k equals Result(2), return R.
- Get the character at position k within Result(1).
- If Result(6) is one of the 69 nonblank ASCII characters ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz 0123456789 @*_+-./, go to step 14. - Compute the 16-bit unsigned integer that is the Unicode character encoding of Result(6).
- If Result(8), is less than 256, go to step 12.
- Let S be a string containing six characters “%uwxyz” where wxyz are four hexadecimal digits encoding the
value of Result(8). - Go to step 15.
- Let S be a string containing three characters “%xy” where xy are two hexadecimal digits encoding the
value of Result(8). - Go to step 15.
- Let S be a string containing the single character Result(6).
- Let R be a new string value computed by concatenating the previous value of R and S.
- Increase k by 1.
- Go to step 5.
which can be coded like this:
(function(global) {
var allowed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./,';
global.escapeString = function(str) {
str = str.toString();
var len = str.length, R = '', k = 0, S, chr, ord;
while(k < len) {
chr = str[k];
if (allowed.indexOf(chr) != -1) {
S = chr;
} else {
ord = str.charCodeAt(k);
if (ord < 256) {
S = '%' + ("00" + ord.toString(16)).toUpperCase().slice(-2);
} else {
S = '%u' + ("0000" + ord.toString(16)).toUpperCase().slice(-4);
}
}
R += S;
k++;
}
return R;
};
})(typeof window == 'undefined' ? global : window);
How do I escape a single quote ( ' ) in JavaScript?
You should always consider what the browser will see by the end. In this case, it will see this:
<img src='something' onmouseover='change(' ex1')' />
In other words, the "onmouseover" attribute is just change(
, and there's another "attribute" called ex1')'
with no value.
The truth is, HTML does not use \
for an escape character. But it does recognise "
and '
as escaped quote and apostrophe, respectively.
Armed with this knowledge, use this:
document.getElementById("something").innerHTML = "<img src='something' onmouseover='change("ex1")' />";
... That being said, you could just use JavaScript quotes:
document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(\"ex1\")' />";
Related Topics
Sort Mixed Alpha/Numeric Array
When Is the Body of a Promise Executed
Why Is {} + {} No Longer Nan in Chrome Console
Generating Non-Repeating Random Numbers in Js
How to Do Outerhtml in Firefox
How to Use Onclick() or Onselect() on Option Tag in a Jsp Page
How to Create a Function from a String with JavaScript
How to Convert Date to Timestamp
Check If Event Exists on Element
Detecting When a Div's Height Changes Using Jquery
Getting Scroll Bar Width Using JavaScript
What Is the Cleanest Way to Get the Progress of Jquery Ajax Request
JavaScript Thousand Separator/String Format
Sending Credentials with Cross-Domain Posts
How Many Bytes in a JavaScript String
JavaScript - How to Extract Filename from a File Input Control