string with quotes

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mpl
    New Member
    • Sep 2007
    • 27

    string with quotes

    Hi,
    Below is my javascript string which i will be using in asp.net

    Code:
     sTemp = "<script language=javascript>;parent.document.getElementById('ctl00$ContentPlaceHolder1$txt_name').value ='" + myname + " ' ;</script>"
    ClientScript.RegisterStartupScript(Me.GetType, "myscript", sTemp)

    variable myname is having single quotes values (myname =John O'Loughlin
    ) .I get javascript error (Expected ';') when i register the script

    any solution to assign value with variables having single quotes?

    Thanks
    Mpl
    Last edited by gits; Jul 31 '08, 06:44 AM. Reason: added code tags
  • rohypnol
    New Member
    • Dec 2007
    • 54

    #2
    Hello,

    This is more of a .NET question... To paste the contents of the variable you should escape the quotes with a backslash. Replace every quote with backslash+quote .
    But keep in mind, this is still dangerous so please check this http://www.google.com/search?hl=en&q...ng&btnG=Search The first link it returns is http://www.west-wind.com/weblog/posts/114530.aspx which I've found to be very helpful for what you need.
    Code:
    /// <summary>
    /// Encodes a string to be represented as a string literal. The format
    /// is essentially a JSON string.
    /// 
    /// The string returned includes outer quotes 
    /// Example Output: "Hello \"Rick\"!\r\nRock on"
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static string EncodeJsString(string s)
    {
    	StringBuilder sb = new StringBuilder();
    	sb.Append("\"");
    	foreach (char c in s)
    	{
    		switch (c)
    		{
    			case '\"':
    				sb.Append("\\\"");
    				break;
    			case '\\':
    				sb.Append("\\\\");
    				break;
    			case '\b':
    				sb.Append("\\b");
    				break;
    			case '\f':
    				sb.Append("\\f");
    				break;
    			case '\n':
    				sb.Append("\\n");
    				break;
    			case '\r':
    				sb.Append("\\r");
    				break;
    			case '\t':
    				sb.Append("\\t");
    				break;
    			default:
    				int i = (int)c;
    				if (i < 32 || i > 127)
    				{
    					sb.AppendFormat("\\u{0:X04}", i);
    				}
    				else
    				{
    					sb.Append(c);
    				}
    				break;
    		}
    	}
    	sb.Append("\"");
    
    	return sb.ToString();
    }
    Regards,
    Tom

    Comment

    Working...