JavaScript Strings¶
JavaScript strings are for storing and manipulating text. They are written inside quotes (single or double).
Basic Usage¶
String Length¶
The length property returns the number of characters in a string.
String Methods¶
JavaScript has many built-in methods to work with strings (remember: strings are Immutable).
| Method | Description |
|---|---|
slice(start, end) |
Extracts a part of a string. |
substring(start, end) |
Similar to slice. |
replace(old, new) |
Replaces a specified value with another. |
toUpperCase() |
Converts to upper case. |
toLowerCase() |
Converts to lower case. |
trim() |
Removes whitespace from both sides. |
charAt(index) |
Returns the character at a specific index. |
includes(str) |
Returns true if the string contains str. |
Template Literals (ES6)¶
Template Literals use back-ticks (`) instead of quotes. They are the modern standard for handling complex strings.
1. Multiline Strings¶
2. Interpolation (Variables in Strings)¶
Backslash Escaping
If you need to use a quote inside a string of the same type, use the backslash \ escape character:
let text = "We are the so-called \"Vikings\" from the north.";