i have the following code:
var name = "Joe O'Neal";
var row= [];
row.push(
"<td><input type='hidden' name='milestones[" + id + "].Name'
value='" + name + "' class='currentRowName' />
<span class='currentRowNameText'>" + name + "</span></td>")
but the issue is that i have a situation where there is an apostrophe in the name variable so it causes problems with this:
value='" + name + "'
what is the correct way to write this to avoid any conflicts with apostrophes? In C#, i would do something like
value=\"" + name + "\"
but that doesn't seem to work in javascript
What you're looking to do is sanitize your input. To do this, you might define a helper method which replaces any unsafe characters with either the Unicode equivalent or the HTML entity. Not only is this sort of thing used for escaping quotes, but it can also help prevent things like XSS Attacks.
The following is adapted from Tom Gruner's answer from this other question on Escaping HTML strings with jQuery.
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
function escapeHtml(string) {
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
}
And then to use this, you would do something like the following:
var name = "Joe O'Neal";
var safe_name = escapeHtml(name);
var row= [];
row.push(
"<td><input type='hidden' name='milestones[" + id + "].Name'
value='" + safe_name + "' class='currentRowName' />
<span class='currentRowNameText'>" + safe_name + "</span></td>");
If you find yourself doing this a lot, then it may be time to start using a template library which can do this automatically. One template library I recommend and find useful is the Google Closure Templates. It is an enterprise-grade template library which will (by default) sanitize your HTML.
For more information on how Closure Templates help protect you, you can check out the page they have on security.