Javascript String








The String type represents a sequence of 16-bit Unicode characters. Strings can be created by either double quotes (") or single quotes ('). The quotes must match(start with " end with ").

Both of the following are legal:

var firstName = "first";
var lastName = 'last';

A string beginning with a double quote must end with a double quote, and a string beginning with a single quote must end with a single quote.

For example, the following will cause a syntax error:

var firstName = 'a string";    //syntax error - quotes must match

var firstName = "first"; 
var lastName = 'last';
console.log(firstName);
console.log(lastName);

The code above generates the following result.





String Escape

To input non-inputable value we have to use escapes. The escapes start with a \.

EscapeMeanings
\nNew line
\tTab
\bBackspace
\rCarriage return
\fForm feed
\\Backslash (\)
\'Escape single quote (')
\"Escape double quote (")
\xnnA character represented by hexadecimal code nn.
\unnnnA Unicode character represented by the hexadecimal code nnnn.

These character literals can be included anywhere with a string and will be interpreted as if they were a single character.

var text = "This is the letter sigma: \u03a3.";

The string in the code above is 28 characters long even though the escape sequence is 6 characters long. The entire escape sequence represents a single character, so it is counted as 1.

The following code uses the escape sequence to input string values.


console.log("\"");
console.log('\'');
console.log('\x42');
console.log("\u03a3");

The code above generates the following result.





String length

The string length is the number of 16-bit characters in the string.

The length of any string can be returned by using the length property as follows:


var text = "This is a test.";
console.log(text.length); 

The length of a string can be returned by using the length property:


var firstName = 'first';
console.log(firstName.length);

The code above generates the following result.