Escape apostrophe when passing parameter in onclick event

RememberME picture RememberME · May 17, 2010 · Viewed 25.5k times · Source

I'm passing the company name to an onclick event. Some company names have apostrophes in them. I added '.Replace("'", "'")' to the company_name field. This allows the onclick event to fire, but the confirm message displays as "Jane&# 39;s Welding Company".

<a href="#" onclick="return Actionclick('<%= Url.Action("Activate", new {id = item.company_id}) %>', '<%= Html.Encode(item.company1.company_name.Replace("'", "&#39;")) %>');" class="fg-button fg-button-icon-solo ui-state-default ui-corner-all"><span class="ui-icon ui-icon-refresh"></span></a>

<script type="text/javascript">
function Actionclick(url, companyName) 
{
    if (confirm('This action will activate this company\'s primary company ('+companyName+') and all of its other subsidiaries.  Continue?')) 
    {
        location.href = url;
    };
};

EDIT The confirm message shows the &# 39; in the message rather than the '. When I typed it out here, it replaced the &# 39; with a '. Added spaces so that wouldn't happen. I want to know the best way to pass it to my onclick event and also properly display it in the message without doing multiple replaces (if there is a better way).

Answer

Brenton Alker picture Brenton Alker · May 17, 2010

There are two options as I see it.

  1. If you wrap the parameters in quotes (") instead of apostrophes/single quotes (') then you shouldn't need to escape it at all. HTML encoding will take care of encoding any quotes (if they are in the string) and the apostrophe's won't be a problem. Though, as the javascript is already wrapped in quotes, you will need to backslash escape your quotes. eg:

    onclick="return Actionclick(\"<%= Url.Action("Activate", new {id = item.company_id}) %>\", \"<%= Html.Encode(item.company1.company_name) %>\");"

  2. Backslash escape the company name as it's only the final javascript string that needs the apostrophe escaped, not the HTML. eg:

    onclick="return Actionclick('<%= Url.Action("Activate", new {id = item.company_id}) %>', '<%= Html.Encode(item.company1.company_name.Replace("'", "\\'")) %>');"