JavaScript:Strings

String Literals

 * A string literal is zero or more characters enclosed in double (") or single (') quotation marks.
 * A string must be delimited by quotation marks of the same type; that is, either both single quotation marks or both double quotation marks.
 * The following are examples of string literals:
 * "qwerty"
 * 'qwerty'
 * "1234"
 * "first line \n second line"
 * You can call any of the methods of the String object on a string literal value—JavaScript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object.

Special characters

 * The following table lists the special characters that you can use in JavaScript strings.

Length (js4_01)


Example js4_01

indexOf .. example (js4_02)




Example js4_02

match .. example (js4_03)




Example js4_03

substr/substring .. example (js4_04)




Example js4_04

toUpperCase/toLowerCase .. example (js4_05)
Example :.

LeftStr .. example (js4_06)
Some languages provide Left, Right and Mid string functions. JavaScript requires you to write your own (there is a sneaky way to do this using the split method and arrays but we'll leave that until arrays are covered). B. Devington Rayan (2002) describes the JavaScript Left and Right string. A modified version is as follows:

Example :.

Exercise: Using String methods to reverse text (js4_07)
Create a JavaScript that takes "Firstname Lastname" input and reverses it to "Lastname, Firstname".
 * For example "Neil Coomber" is converted to "Coomber, Neil"

Example :.