Why Do Quotes Sometimes Cause Trouble?

Search

 by Remas Wojciechowski

Whenever it comes to using quotes in ASP, there's likely to some trouble with them. The thing is, quotes are both normal and special characters. The special meaning of quotes is that of being string delimiters. More specifically, double quotes (") delimit strings in VBScript and single quotes (') delimit quotes in SQL.

Remember:

  • Single quotes delimit strings in SQL
  • Double quotes delimit strings in VBScript

Problems occur e.g. when you want to add Ms. O'Connel to your user database or when you use Response.Write to output double quotes.

The default interpretation of a quote character is that of a string delimiter (special meaning). That is why quotes need to be escaped if you intend to use their character meaning. To escape quotes, you have to double them, i.e. use "" for a double quote character in a VBScript string and '' for a singe quote character in an SQL string.

Escaping single quotes:

strName = Replace("O'Connel", "'", "''")

Output quotes in VBScript:

Response.Write("Quotes ""living in"" a string must be doubled!")

You've noticed, that there are pretty many double quotes involved. In fact, many programmers consider that representation hardly legible. Some prefer using the Chr() function, some use constants. I presonally like the constants approach.

Escaping double quotes with Chr(34):

Response.Write("Quotes " & Chr(34) & "living in" & Chr(34) & " a string must be doubled!")

Escaping double quotes with constants:

Const DOUBLE_QUOTE = """"
Response.Write("Quotes " & DOUBLE_QUOTE & "living in" & DOUBLE_QUOTE & " a string must be doubled!")