Searching and slicing strings
A string answers two kinds of question: whether a piece of text is inside it, and which piece stands at a position. The first kind is includes and the index functions, the second is slice and substring. All of them are read-only, so every answer is a new string or a number and the original keeps its value.
The two slicing methods look interchangeable until an argument is negative or the positions are written the wrong way round, and then they disagree. This lesson prints the same calls on the same string for both, then uses the difference in one program that reads a file name apart. The next lesson builds text out of the pieces, and the part after that covers the patterns that find text no plain search can.
includes and the index functions
includes answers a boolean, and the comparison is case-sensitive: a search for guide does not find Guide. indexOf answers the position of the first match and -1 when there is none, which is the value a condition has to test for because zero is a valid position. startsWith and endsWith test the two ends without slicing the string first.
const title = 'JavaScript: The Definitive Guide';
console.log('includes Guide:', title.includes('Guide'));
console.log('includes guide:', title.includes('guide'));
console.log('indexOf The:', title.indexOf('The'));
console.log('indexOf Rust:', title.indexOf('Rust'));
console.log('lastIndexOf a:', 'a-b-a'.lastIndexOf('a'));
console.log('startsWith JavaScript:', title.startsWith('JavaScript'));
console.log('endsWith Guide:', title.endsWith('Guide'));
console.log('includes Java from 5:', title.includes('Java', 5));
console.log('indexOf e:', title.indexOf('e'));
console.log('indexOf e from 15:', title.indexOf('e', 15));
node searching.js
includes Guide: true
includes guide: false
indexOf The: 12
indexOf Rust: -1
lastIndexOf a: 4
startsWith JavaScript: true
endsWith Guide: true
includes Java from 5: false
indexOf e: 14
indexOf e from 15: 17
The missing word came back as -1 and the found one as a position, so a test written as if (title.indexOf('The')) would be true for every match except one at position zero. The optional second argument moves the start of the search: the first e stands at fourteen and the search from fifteen finds the next one at seventeen, without wrapping around to the beginning. A search that has to ignore case lowers both sides once and searches the lowered copies.
slice
slice(start, end) returns the characters from start up to but not including end. A negative position counts from the end, an omitted end runs to the end of the string, and a position past the end is clamped instead of throwing. An end before the start gives an empty string rather than an error, which makes the method safe on data a program has not checked.
const text = 'abcdefghij';
console.log('slice(0, 3):', text.slice(0, 3));
console.log('slice(3):', text.slice(3));
console.log('slice(-3):', text.slice(-3));
console.log('slice(2, -2):', text.slice(2, -2));
console.log('slice(5, 2) is empty:', text.slice(5, 2) === '');
console.log('slice(-100, 2):', text.slice(-100, 2));
console.log('slice from a variable:', text.slice(text.indexOf('c'), 6));
node slice.js
slice(0, 3): abc
slice(3): defghij
slice(-3): hij
slice(2, -2): cdefgh
slice(5, 2) is empty: true
slice(-100, 2): ab
slice from a variable: cdef
The negative positions are counted from the end, so slice(-3) is the last three characters and slice(2, -2) drops two at each end. The clamped position is the behaviour to rely on: -100 becomes zero and the call returns the first two characters. The last line is the usual combination, a position found by indexOf and handed to slice.
substring and the differences
substring takes the same two arguments and reads them differently. A negative or missing value becomes zero, and when the first argument is larger than the second the two are swapped, so the call always returns something. That is a convenience when the arguments come from somewhere unpredictable and a source of surprise when a negative index was meant to count from the end, where the answer is the whole string from zero.
const text = 'abcdefghij';
console.log('substring(0, 3):', text.substring(0, 3));
console.log('substring(3, 0):', text.substring(3, 0));
console.log('substring(-3):', text.substring(-3));
console.log('substring(2, -2):', text.substring(2, -2));
console.log('slice(3, 0) is empty:', text.slice(3, 0) === '');
console.log('slice(-3):', text.slice(-3));
console.log('substring(-3) is everything:', text.substring(-3) === text);
node substring.js
substring(0, 3): abc
substring(3, 0): abc
substring(-3): abcdefghij
substring(2, -2): ab
slice(3, 0) is empty: true
slice(-3): hij
substring(-3) is everything: true
The two calls with the same arguments gave the same answer when both were positive, and the calls with a negative one split apart: substring(-3) returned the whole string while slice(-3) returned the last three characters. The swapped case is the other difference: slice(3, 0) is empty and substring(3, 0) is the first three characters. This course uses slice everywhere, because it is the method that also works on arrays and because a negative position is worth having. The older substr takes a length instead of an end and is deprecated.
Reading a file name apart
A program that reads a name knows the separators and not the offsets, so the positions come from indexOf and lastIndexOf and the pieces come from slice. The dot is found from the right, because a name may contain more than one, and the end tests answer the two questions a loader asks before it parses anything.
const file = 'report-2024-05-17.csv';
console.log('stem:', file.slice(0, file.lastIndexOf('.')));
console.log('extension:', file.slice(file.lastIndexOf('.') + 1));
console.log('prefix:', file.slice(0, file.indexOf('-')));
console.log('date part:', file.slice(file.indexOf('-') + 1, file.lastIndexOf('.')));
console.log('is csv:', file.endsWith('.csv'));
console.log('has a date:', file.includes('2024-'));
node parts.js
stem: report-2024-05-17
extension: csv
prefix: report
date part: 2024-05-17
is csv: true
has a date: true
The date part is the whole middle, which the two positions describe without a regular expression. The same code works for a name with no dash, because indexOf returns minus one and slice(0, -1) then means everything but the last character, which is a bug the next run would hide. A parser that has to be right about missing separators tests for minus one first, and the lesson on regular expressions is the other way to state the shape of the name.
Exercises
- Search for the word the in searching.js with both cases. Which method answers -1 and which one returns a position?
- Call text.slice(0, 100) and text.substring(0, 100) in slice.js. Do the two answers differ?
- Print text.slice(3, 3) and text.substring(3, 3). What does each return, and what does that say about an empty range?
- Change the file name in parts.js to notes.txt. Which lines still print a sensible value and which one is now wrong?
- Use lastIndexOf on 'a-b-a' with a start position of 3. Which position arrives, and why is it not the last one?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
includesreturn?Answer
A boolean
includes answers whether the text is there, and indexOf is the method that answers where.
-
What does this program print?
console.log('hello'.indexOf('l'));Answer
2
The first l stands at index two, since the count starts at zero.
-
What does this program print?
console.log('hello'.indexOf('z'));Answer
-1
A missing substring is reported as minus one, which a condition has to test for explicitly.
-
What does this program print?
console.log('abcdef'.slice(-2));Answer
ef
A negative position counts from the end, so slice takes the last two characters.
-
What does this program print?
console.log('abcdef'.substring(4, 1));Answer
bcd
substring swaps its arguments when the first is larger, so the call becomes substring(1, 4).
-
How does
substringtreat a negative argument?Answer
It becomes zero
The method has no negative positions, and it replaces them with zero before it slices.
-
What does this program print?
console.log('abcdef'.slice(4, 1).length);Answer
0
slice does not swap its arguments, and an end before the start gives an empty string of length zero.
-
Which method counts a position from the end of the string?
Answer
slice with a negative argument
slice and at accept negative positions, and substring replaces them with zero.
-
What does this program print?
console.log('report.csv'.endsWith('.csv'));Answer
true
The test asks about the last four characters, and they are the extension.
-
Why does a program test
indexOfagainst-1instead of testing it as a boolean?Answer
Because zero is a valid position and is falsy
A match at the beginning of the string gives zero, which a truthiness test would read as a miss.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev