The string type is considered to be any sequence of 16-bit Unicode characters grouped within double quotes (") or single quotes ('). Both of these examples are valid:

var capCity = "London"; // valid

var capCity = 'Paris'; // valid

var capCity = "Rome'; // not valid

Double quotes and single quotes in JS are interpreted exactly the same but a string started with one type must end with the same.

The length property may be used to determine the number of characters inside a string, as shown here:

var text = "Hello. It has been a nice day";

alert(text.length); // outputs 29

Characters literals

Certain characters in JavaScript have special meanings. They are escaped with a backlash (\) and are not printed on the canvas, but the script rather gives them another meaning.

Following table shows character literals:

Character literals

literal meaning
\n new line
\t tab
\b backspace
\r carriage return
\f form feed
\' single quote ('); used when single quotes are needed inside single quotes delineation. Example: 'Hello \'You\''.
\" double quote ("); used when double quotes are needed inside double quotes delineation. Example: "Hello \"You\"".
\nnn a character represented by octal code nn where n is an octal digit 0-7. Example: \251 is symbol ©.
\xnn a character represented by hexadecimal code nn where n is a hexadecimal digit 0-F. Example: \x41 is letter A.
\unnnn a Unicode character represented by hexadecimal code nnnn where n is a hexadecimal digit 0-F. Example: /u03c0 is symbol for Greek character π.

 

 

 

 

 

 

 

 

 

In the following example we can see the usage of escaping a special character.

var text = "This is the Greek letter PI: \u03c0".

Conversions

There are two ways to convert a value into a string, one can use a method toString() and the other one is a function called String().

The method toString() is available on any value that is a number, a Boolean, an object or a string. If the value is null or undefined this method is not available.

When this method is applied to a number, it may take the radix as a single argument, thus outputting the value as a binary, octal, decimal, hexadecimal, or another valid base; as shown below:

var num = 10;

alert(num.toString()); // "10" (default radix is 10)

alert(num.toString(2)); // "1010"

alert(num.toString(8)); // "12"

alert(num.toString(10)); // "10"

alert(num.toString(16)); //"a"

The String() function has same properties as the toString method but it also evaluates the values null and undefined, returning them in the same form as received but as strings. The example below shows how it works:

var num1 = 10;

var num2;

alert(String(num1)); // "10"

alert(String(num2)); // "undefined"

Example

The string data type example:

 

›› go to examples ››