Search code examples
javascriptstringasp-classicescapingquotes

Pass a string with double and single quotes from asp to javascript function


I have the following code:

PropertyID = 101
PropertyName = "My'complex" property name"" //This is passed from sql query
Response.Write "<a href=""javascript:RenameFunc("& PropertyID & ", '" & PropertyName  & "' )"" onclick=""""></a>"

The problem is that If I have single or double quotes in my variables, the javascript function brakes (which is normal).

I tried escaping them like this:

 Response.Write "<a href=""javascript:RenameFunc("& PropertyID & ", '" & Replace(Replace(PropertyName,"'",""),"""","")  & "' )"" onclick=""""> </a>"

This doesn't break the function, but it removes the quotes from my string and I need them.

I also tried with String.row like this:

Response.Write "<a href=""javascript:RenameFunc("& PropertyID & ", String.raw`"& PropertyName &"` )"" onclick=""""> </a>"

Still no success, but maybe I use it the wrong way.

Is there any other way to pass the string and keep it as it is, without breaking the javascript function?


Solution

  • Use the Server.HTMLEncode() helper:

    Response.Write "<a href=""javascript:RenameFunc("& PropertyID & ", '" & Server.HtmlEncode(Replace(PropertyName,"'","\'")) & "')"" onclick=""""> </a>"
    

    See Documentation