views:

249

answers:

4

Hi all,

I have a MVC view in which I have to pass a string variable to javascript, but that string variable has single quotes in it ('). I am trying to do something like this

<a onclick="JavaScript:AddressHandler.ProcessAddress('<%= homeAddress %>');" 
                            class="button-link">change</a>

homeAddress has single quotes which I have to workaround somehow so that I can pass the complete value of it to the javascript. Any help in this regard is much appreciated.

Thanks!

A: 

I don't have time to test it, but look at HtmlHelper.Encode(string s). It might handle the escaping for you.

Joel Cochran
That does HTML encoding, not Javascript escaping.
Guffa
OK, I wasn't sure if it would do the escaping or not.
Joel Cochran
+1  A: 

To escape a string to be a Javascript string literal, you replace backslash with double backslashes, and the string delimiter with a backslash and the delimiter:

<a onclick="AddressHandler.ProcessAddress('<%= homeAddress.Replace(@"\", @"\\").Replace("'", @"\'") %>');" class="button-link">change</a>

Note: The javascript: protocol is used when you put script in an URL, not as an event handler.

Edit:
If the script also contains characters that need HTML encoding, that should be done after escaping the Javascript string:

<a onclick="<%= Html.Encode("AddressHandler.ProcessAddress('" + homeAddress.Replace(@"\", @"\\").Replace("'", @"\'") +"');") %>" class="button-link">change</a>

So, if you don't know what the string contains, to be safe you need to first escape the string literal, then HTML encode the code so that it can be put in the attribute of the HTML tag.

Guffa
In javascript do I need to convert that back somehow .. or is it automatically handled .. sorry for my noobness. Thanks!
Mahesh Velaga
That single quote is terminating the "Javascript:.. thing :(
Mahesh Velaga
Even after escaping with backslash, any more suggestions ?
Mahesh Velaga
No, you don't have to decode it in the script. The escaping is so that the string can contain the correct characters. If your script contains characters that needs HTML encoding, you need to do that after escaping the Javascript string, se my edit above.
Guffa
@Guffa Thanks for the help, could you please throw some more light into the purpose of javascript: ?
Mahesh Velaga
The protocol is used when you put code in an url: <a href="javascript:alert('Hello.');return false;">speek</a>
Guffa
A: 

You can write a method that escapes all single quotes (and other characters if needed) with a backslash so it is not misunderstood by javascript.

Isac
A: 

You'll want to encode homeAddress as a URL. MVC has a built in helper to do this: UrlHelper.Encode(string url) - it should replace a single quote with %27

James Kolpack
How will I retrive the single quote in javascript, is there a built-in function in javascript to do that? or do I have to parse and replace them ?
Mahesh Velaga