String Literals

by Jan Verhoeven, 25 November 2001

You will use string literals in every programming language: pascal, vcbscript, javascript etc. Each language has its own way of dealing with string literals. When creating ASP pages I  usually have to deal with three different styles: the SQL query style, the server-side vbscript style and the client-side javascript style. What follows is guidance in the use of string literals for those three cases.

VBScript string literals

In VBScript you enclose your strings with double quotes and use the & operator to concatenate strings.

s = "Jan"
s = "Jan" & " Verhoeven"

What if you want to assign "Jan Verhoeven" (including the quotes) to the variable s? In VbScript you can use 2 double quote characters to include a double quote character in the string:

s = """Jan Verhoeven"""

Alternatively you can use the chr(34) construct:

s = chr(34) & "Jan Verhoeven" & chr(34)

When you are building HTML code in an ASP page using string literals you can mix single and double quotes in the HTML:

s = "<a href='somepage.html' title='click here for more'>More...</a>"

 

Javascript string literals

In javascript your are not limited to double quotes like in vbscript. You can use both single and double quotes to delimit strings. But the surrounding quotes must be the same. If you start with a single quote you must also end with one. You use the + operator to concatenate strings.

s = 'Jan Verhoeven'
s = "Jan Verhoeven"
s = 'Jan' + ' Verhoeven'

In vbscript you can use two double quotes to insert a single double quote in a string literal. In javascript you have the use the \ escape character when you want to insert a string delimiter in your string literal:

s = '\'Jan Verhoeven\''
s = '"Jan Verhoeven"'
s = "\"Jan Verhoeven\""

As you can see, because we can use both the ' and " string delimiter in javascript, we have more options. We can easily build the "Jan Verhoeven" string by enclosing it with single quotes.

SQL query string literals

In your ASP pages you will often need to build SQL query strings, a mix of string literal and variable concatenation. In SQL you must use the single quote ' string delimiter:

strSQL="UPDATE t_users SET strUser='Jan Verhoeven' WHERE id_user=" & cstr(id_user)

strSQL="UPDATE t_users SET strUser='" & strName & "' WHERE id_user=" & cstr(id_user)

The above example is for vbscript. In javascript we could do the same thing:

strSQL="UPDATE t_users SET strUser='" + strName + "' WHERE id_user=" + id_user

Note that in javascript the numeric value of a variable is automatically converted to a string when used in a string concatenation and when preceeded by string literals.

SQL allows you to use 2 single quotes to insert a single quote in the literal:

strSQL='UPDATE t_users SET strUser=''' + strName + ''' WHERE id_user=' + id_user

This is also the method you would use in Delphi (object Pascal).