The length of string is the number of 16-bit values it contains. Usually one character corresponds to one 16-bit value, but some rarely used unicode characters are encoded as a sequence of two 16-bit values. That means that string with one character may have a length of 2. To read a string length use length property:
var s = "a"; console.log(s.length); //1
To concatenate strings use + operator on them:
var name = "Graham"; var city = "Dublin"; var text = name + " lives in " + city; console.log(text); //Graham lives in Dublin
To create string simply surround sequence of characters with double (“) or single (‘) quotes. There is no difference between them, just be consistent and use a pair of the same characters, otherwise an error will occur:
For example to place an singe apostrophe character inside a string surrounded by single quotes (similarly for double apostrophes), you must use the backslash character to “escape” this apostrophe:
var text = 'Don't worry, I'm fine';
Backslash and the following character form a escape sequence that represents special characters. Below a list of several useful escape sequences:
- ‘ – single quote,
- ” = double quote,
- \ – backslash,
- n – new line,
- r – carriage return,
- t – tab.
Any character can be presented by specifying its latin one or unicode character code as a hexadecimal number:
xdd – a latin-1 character specified by the two hexadecimal digits (dd),
udddd – a unicode character specified by the four hexadecimal digits (dddd).
String – a primitive data type and object
Values of type string are not objects, and string is a primitive data type. However you can read property length from string type value, you can also invoke number of methods from string type value.
var s = "String data type"; //primitive string var char = s.charAt(7); // string is temporarily converted to object to call method console.log(char); // d
See String methods.