Searching Inside a String
Four methods answer the question of whether and where one piece of text appears inside another.
includes answers yes or no, indexOf gives the position or -1, startsWith and endsWith check the edges. All four are case sensitive, so normalise first when a person typed the text.
EXERCISE
1includes: Yes or No
The simplest search question is whether some text appears at all, and one method answers it with a boolean.
includes returns true or false:
const email = "ada@example.com";
console.log(email.includes("@")); // true
console.log(email.includes("example")); // true
console.log(email.includes("gmail")); // false
It is case sensitive, which is the usual trap:
const title = "The Hobbit";
console.log(title.includes("hobbit")); // false !
console.log(title.includes("Hobbit")); // true
// Normalise both sides when a person typed one of them:
console.log(title.toLowerCase().includes("hobbit".toLowerCase())); // true
A second argument says where to start looking:
const text = "abcabc";
console.log(text.includes("abc")); // true found at 0
console.log(text.includes("abc", 1)); // true found at 3
console.log(text.includes("abc", 4)); // false nothing left
Putting it to work:
function looksLikeEmail(value) {
return value.includes("@") && value.includes(".");
}
console.log(looksLikeEmail("ada@example.com")); // true
console.log(looksLikeEmail("not-an-email")); // false
// A real email check is far stricter than this.
// For a first pass in a form, this catches the obvious mistakes.
includes is the method to reach for whenever the answer you need is yes or no, because it says exactly that and reads as English inside an if. Only move to indexOf when you actually need to know where, which is less often than beginners expect.
EXERCISE
2indexOf: Where, or Minus One
When the position matters, indexOf gives it to you, and its answer for not-found is a value worth understanding.
indexOf returns a position, counting from zero:
const text = "hello world";
console.log(text.indexOf("hello")); // 0
console.log(text.indexOf("world")); // 6
console.log(text.indexOf("o")); // 4 the FIRST one
console.log(text.indexOf("xyz")); // -1 not found
Minus one means not found, and it is not falsy:
const text = "hello";
// This looks right and is wrong:
if (text.indexOf("h")) {
console.log("found"); // does NOT run: indexOf returned 0, which is falsy
}
// Compare against -1 explicitly:
if (text.indexOf("h") !== -1) {
console.log("found"); // runs
}
// Or just use includes, which is why it was added:
if (text.includes("h")) {
console.log("found"); // runs
}
lastIndexOf searches from the end:
const path = "folder/sub/file.txt";
console.log(path.indexOf("/")); // 6
console.log(path.lastIndexOf("/")); // 10
console.log(path.lastIndexOf(".")); // 14
// Which is how you get a file extension:
const dot = path.lastIndexOf(".");
console.log(path.slice(dot + 1)); // txt
Both are case sensitive, like includes:
console.log("Hello".indexOf("h")); // -1
console.log("Hello".indexOf("H")); // 0
Pro Tip: The
indexOf(...) !== -1check exists in an enormous amount of older JavaScript, written beforeincludeswas added, and theif (text.indexOf(x))bug is exactly why. When a match at position 0 is the most likely case, a truthiness check onindexOfsilently reports not found.
EXERCISE
3startsWith and endsWith
Checking the beginning or the end of a string is common enough that both have their own method.
Checking the start:
const url = "https://devloom.dev/courses";
console.log(url.startsWith("https://")); // true
console.log(url.startsWith("http://")); // false
function isSecure(link) {
return link.startsWith("https://");
}
console.log(isSecure("http://example.com")); // false
Checking the end:
const file = "report.pdf";
console.log(file.endsWith(".pdf")); // true
console.log(file.endsWith(".docx")); // false
function isImage(name) {
const lower = name.toLowerCase();
return lower.endsWith(".jpg") || lower.endsWith(".png");
}
console.log(isImage("Photo.PNG")); // true
console.log(isImage("notes.txt")); // false
startsWith takes a position too:
const text = "abcdef";
console.log(text.startsWith("cd")); // false
console.log(text.startsWith("cd", 2)); // true start looking at index 2
Choosing between the four:
const text = "hello world";
text.includes("world"); // is it in there? -> true
text.indexOf("world"); // where is it? -> 6
text.startsWith("hello"); // does it begin with? -> true
text.endsWith("world"); // does it end with? -> true
// All four are case sensitive. All four take a string to look for.
Pro Tip: Pick the method that matches the question you are actually asking, because the code then says what it means.
file.endsWith(".pdf")states the rule directly, whilefile.indexOf(".pdf") === file.length - 4computes the same answer and makes the next reader work out why.
