Appearance
Strings
The string in JavaScript is represented by characters enclosed in ''
or ""
.
If '
itself is a character, it can be enclosed in ""
, such as "I'm OK,"
which contains the characters I
, '
, m
, space, O
, K
—totaling six characters.
If the string contains both '
and "
, you can use the escape character \
to indicate this, for example:
javascript
'I\'m \"OK\"!'; // I'm "OK"!
The string content represented is: I'm "OK"!
The escape character \
can escape many characters, such as \n
for a new line and \t
for a tab. The character \
itself also needs to be escaped, so \\
represents the character \.
ASCII characters can be represented in hexadecimal as \x##
, for example:
javascript
'\x41'; // equivalent to 'A'
You can also use \u#### to represent a Unicode character:
javascript
'\u4e2d\u6587'; // equivalent to '中文'
Multi-line Strings
Since multi-line strings are cumbersome to write with \n, the latest ES6 standard introduces a new way to represent multi-line strings using backticks ...
:
javascript
`This is a
multi-line
string`;
Note: The backtick is located below the ESC key, to the left of the number key 1:
┌─────┐ ┌─────┬─────┬─────┬─────┐
│ ESC │ │ F1 │ F2 │ F3 │ F4 │
└─────┘ └─────┴─────┴─────┴─────┘
┌─────┬─────┬─────┬─────┬─────┐
│ ~ │ ! │ @ │ # │ $ │
│ ` │ 1 │ 2 │ 3 │ 4 │
├─────┴──┬──┴──┬──┴──┬──┴──┬──┘
│ │ │ │ │
│ tab │ Q │ W │ E │
├────────┴──┬──┴──┬──┴──┬──┘
│ │ │ │
│ caps lock │ A │ S │
└───────────┴─────┴─────┘
Exercise: Test if your browser supports ES6. If not, represent multi-line strings using \n:
javascript
// If the browser does not support ES6, it will throw a SyntaxError:
console.log(`Multi-line
string
test`);
Template Strings
To concatenate multiple strings, you can use the +
operator:
javascript
let name = 'Xiao Ming';
let age = 20;
let message = 'Hello, ' + name + ', you are ' + age + ' years old!';
alert(message);
If there are many variables to concatenate, using +
can be cumbersome. ES6 introduces template strings, which have the same representation as the above multi-line strings but automatically replace variables within the string:
javascript
let name = 'Xiao Ming';
let age = 20;
let message = `Hello, ${name}, you are ${age} years old!`;
alert(message);
Exercise: Test if your browser supports ES6 template strings. If not, change the template string to a normal string using +
:
javascript
// If the browser supports template strings, it will replace the variables within the string:
let name = 'Xiao Ming';
let age = 20;
console.log(`Hello, ${name}, you are ${age} years old!`);
String Operations
Common string operations are as follows:
Getting the string length:
javascript
let s = 'Hello, world!';
s.length; // 13
To get a character at a specific position in the string, use index operations similar to arrays, with indices starting from 0:
javascript
let s = 'Hello, world!';
s[0]; // 'H'
s[6]; // ' '
s[7]; // 'w'
s[12]; // '!'
s[13]; // undefined An out-of-bounds index does not throw an error but returns undefined.
It's important to note that strings are immutable; assigning a value to a specific index of a string does not result in any error but has no effect:
javascript
let s = 'Test';
s[0] = 'X';
console.log(s); // s remains 'Test'
JavaScript provides some common methods for strings. Note that calling these methods does not change the original string but returns a new string:
toUpperCase
toUpperCase()
converts a string to uppercase:
javascript
let s = 'Hello';
s.toUpperCase(); // returns 'HELLO'
toLowerCase
toLowerCase()
converts a string to lowercase:
javascript
let s = 'Hello';
let lower = s.toLowerCase(); // returns 'hello' and assigns it to variable lower
lower; // 'hello'
indexOf
indexOf()
searches for the position of a specified string:
javascript
let s = 'hello, world';
s.indexOf('world'); // returns 7
s.indexOf('World'); // not found, returns -1
substring
substring()
returns a substring from specified indices:
javascript
let s = 'hello, world';
s.substring(0, 5); // returns 'hello' from index 0 to 5 (excluding 5)
s.substring(7); // returns 'world' from index 7 to the end.