Escaping HTML strings with jQuery
Since you're using jQuery, you can just set the element's text
property:
// before:
// <div class="someClass">text</div>
var someHtmlString = "<script>alert('hi!');</script>";
// set a DIV's text:
$("div.someClass").text(someHtmlString);
// after:
// <div class="someClass"><script>alert('hi!');</script></div>
// get the text in a string:
var escaped = $("<div>").text(someHtmlString).html();
// value:
// <script>alert('hi!');</script>
Escape HTML using jQuery
That's a pretty standard way of doing it, my version used a <div>
though:
return $('<div/>').text(t).html();
This isn't technically 100% safe though as Mike Samuel notes but it is probably pretty safe in practice.
The current Prototype.js does this:
function escapeHTML() {
return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
But it used to use the "put text in a div and extract the HTML" trick.
There's also _.escape
in Underscore, that does it like this:
// List of HTML entities for escaping.
var htmlEscapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/'
};
// Regex containing the keys listed immediately above.
var htmlEscaper = /[&<>"'\/]/g;
// Escape a string for HTML interpolation.
_.escape = function(string) {
return ('' + string).replace(htmlEscaper, function(match) {
return htmlEscapes[match];
});
};
That's pretty much the same approach as Prototype's. Most of the JavaScript I do lately has Underscore available so I tend to use _.escape
these days.
JQuery - Add regular HTML along with escaped HTML
The reason the code in your question didn't work is because all the entities like &
in the Javascript are parsed as the characters they represent when the JS in the HTML is parsed. It would work if you put the code in an external .js
file, since that's not parsed as HTML. Or you could double-encode them:
var map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
But a better way is to create the <h1>
and <p>
elements separately, and put the escaped text in the paragraph using a jQuery method.
const data = '<scr' + 'ipt>alert("foo");</scr' + 'ipt>';
$("#element").prepend("<h1>Heading</h1>", $("<p>", {text: data}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="element"></div>
Do I need to escape string if I use .html() in jQuery?
As its says in JQuery docs:
Unlike the .html() method, .text() can be used in both XML and HTML
documents. The result of the .text() method is a string containing the
combined text of all matched elements. (Due to variations in the HTML
parsers in different browsers, the text returned may vary in newlines
and other white space.)The .text() method cannot be used on form inputs or scripts. To set or
get the text value of input or textarea elements, use the .val()
method. To get the value of a script element, use the .html() method.
so if u just want to output a dollar sign, .text() would be safe as its value would be parsed as string...
How to escape html tags and show it in jquery?
It is a issue to convert string containning escape character into raw html inner string.
Keep other code snippet unchanged.
$(function(){
$.getJSON("test-json.php", function(data) {
$.each(data,function(i,item){
alert(item.content);
var tr = "<tr><td>" + item.title + "</td>" +
"<td>" + $('<div/>').text(item.content).html() + "</td>" +
"<td>" + item.author + "</td>" +
"<td>" + item.email + "</td>" +
"<td>" + item.ip + "</td></tr>"
$("#disp").append(tr);
});
});
});
The core concept is create a virtual jquery html containner,then text(target-string).html().
$('<div/>').text(item.content).html()
How to escape Javascript in HTML string
You need to concatenate strings and variables like so:
read_html += '<img src="https://example.org/' + val.poster_path + '">';
Snippet:
var val = {
poster_path: "something.html"
}
var read_html = '<img src="https://example.org' + val.poster_path + '">';
console.log(read_html)
jquery - how to escape html to prevent XSS?
You should use jQuery text() to encode the data.
$('#mydata').text(data);
EDIT: To create the content of #mydata you can use
$('#mydata')
.html("")
.append($("<h2></h2>").text(response.name))
.append($("<p></p>").text(response.description))
Escaping HTML special character with JSP or JQuery
Here is one way - seeing you already have the data on the page
<td class="description hide" id="${doc.id}"><c:out value="${doc.description}"/></td>
where
.hide is {display:none}
and then
$("#${doc.id}").show();
Related Topics
Getting the Client'S Time Zone (And Offset) in JavaScript
How to Check If an Object Is an Array
What Is a Good Regular Expression to Match a Url
Chrome Extension Message Passing: Response Not Sent
Events Triggered by Dynamically Generated Element Are Not Captured by Event Handler
What Is the Temporal Dead Zone
Get the Current Url With JavaScript
How to Find the Sum of an Array of Numbers
JavaScript: Natural Sort of Alphanumerical Strings
Resolve Promises One After Another (I.E. in Sequence)
What Is the Purpose of Node.Js Module.Exports and How to Use It
Get JavaScript Object from Array of Objects by Value of Property
How to Declare a Namespace in JavaScript
Difference Between a Function Expression VS Declaration in JavaScript
Is It Bad Practice to Have a Constructor Function Return a Promise
Remove Duplicate Values from Js Array
How to Use a Variable in a Regular Expression
JavaScript Object: Access Variable Property by Name as String