JavaScript strings are simple values that you cannot change, and they come with a large set of useful methods attached to them. Most of those methods earn their place in your work, and a few of them are traps that surprise people. This lesson covers the ones that you will actually reach for, and it points out the two that quietly behave in ways you do not expect. This is the first lesson in the module, and the four lessons that follow it build directly on what you learn here: template literals for building text, splitting and joining for turning text into pieces, searching and replacing for finding things inside text, and cleaning and validating for the text that real people type into a form.
This is the first lesson in the JavaScript Strings module, and the next lesson in this module is about "Template Literals in Real Code".
How do I get the length of a string and read a character?
Every string has a length, and that includes the empty string, whose length is zero. To read a single character, use at(). It is the only spelling that accepts a negative index, which means you can ask for the last character without working out the length first.
const label = 'JavaScript';
console.log(label.length); // 10
console.log(label.at(0)); // J
console.log(label.at(-1)); // t
console.log(label[label.length - 1]); // t
console.log(label.charAt(1)); // a
charAt is the older spelling, and it still works. The difference is that it gives you an empty string when the index is out of range, while at() gives you undefined. Prefer at(), partly because the negative index saves you from writing length - 1 every single time. There is one thing to remember about all of these methods. Strings cannot be changed, so every one of them returns a new value and leaves the original exactly as it was.
How do I take a part of a string?
slice() takes a start index and an end index, and it gives you the text between them. The end index is not included, and negative indices count back from the end of the string.
const path = '/api/v1/users';
console.log(path.slice(1, 4)); // api
console.log(path.slice(-4)); // sers
console.log(path.slice(0, -5)); // /api/v1/
console.log(path.slice(2)); // pi/v1/users
The third line is the one that people miss. A negative end index drops that many characters from the end, and it does not count from the start. slice is also forgiving, because an index that reaches beyond the end of the string gives you an empty string instead of an error, which makes it safe to run on text that a user typed. substring exists as well, but it treats negative numbers as zero and it swaps its two arguments when they arrive in the wrong order, so slice is nearly always the clearer choice.
How do I check whether a string contains something?
For a simple yes-or-no question, includes is the one to remember. startsWith and endsWith are the specialised versions for the two ends of the string.
const email = '[email protected]';
console.log(email.includes('@')); // true
console.log(email.endsWith('.com')); // true
console.log(email.startsWith('ada')); // true
console.log(email.indexOf('@')); // 3
Matching is case sensitive, so email.includes('EXAMPLE') is false. If you need to search without caring about the case, lower-case both sides with email.toLowerCase().includes('example'), or use a regular expression with the i flag. The lower-case version is usually clearer, and it saves you from reaching for a pattern that you do not really need.
What do trim, repeat and padStart do?
Three small methods turn up in formatting code far more often than you would expect.
const raw = ' spaced ';
console.log(JSON.stringify(raw.trim())); // "spaced"
console.log('ab'.repeat(3)); // ababab
console.log('42'.padStart(4, '0')); // 0042
console.log('7'.padStart(3, '-')); // --7
trim removes the whitespace from both ends and gives you back a new string, which is why assigning the result is the step that people forget. Calling raw.trim() and then printing raw shows you the original, completely unchanged. repeat duplicates a string a set number of times. padStart and padEnd add padding until the string reaches the length that you asked for, which is how you zero-pad an order number or line up a column of values.
Why is string length sometimes wrong?
The one place length surprises you is text that contains characters outside the basic multilingual plane, such as emoji. Each of those is made of two code units, so length counts them twice.
const wave = '\u{1F44B}';
console.log(wave.length); // 2
console.log([...wave].length); // 1
Spreading the string with ... splits it into code points instead of code units, and that is why the second number is the one that a human would call the length. The same trick fixes the problem of slicing the last character off a string that ends in an emoji. slice(-2) cuts a surrogate pair in half and produces a broken character, while Array.from(text).at(-1) returns the whole one. For plain text the two numbers agree, and that is exactly why this bug only ever shows up in production.
There is a related trap with slice on text that contains combining characters, which are letters built from several code points, such as some accented letters written in decomposed form. There the character count is right but the character boundaries are not, and the fix is the same one. Normalise the text first, and then work with code points rather than code units.
Which string methods should I memorise?
| Method | Returns | Note |
|---|---|---|
str.length | Number of UTF-16 code units | Emoji count as two |
str.at(i) | Character at an index | Accepts negatives; undefined out of range |
str.slice(a, b) | Text between two indexes | End is exclusive; negatives count from the end |
str.includes(x) | A boolean | Case sensitive |
str.startsWith(x) and endsWith(x) | A boolean | Case sensitive |
str.trim() | String without outer whitespace | Returns a new string |
str.repeat(n) | The string n times | n must be a whole number |
str.padStart(len, pad) | A padded string | There is also padEnd |
str.toUpperCase() and toLowerCase() | A case-converted copy | Use the locale versions for locale rules |
Try it yourself: write a file called labels.js and store ' order-0042 ' in a variable. Print the length before trimming and the length afterwards, so that you can see the difference. Use padStart to turn '42' into '0042' and print it. Use startsWith to check whether the trimmed value starts with 'order-', and includes to check whether it contains a dash. Then use slice to pull out just the numeric part, and use Number to turn it into the number 42. Finish by printing the last character with at(-1), and print the character count again with [...text].length so that you can compare the two numbers.