Find Text on a Page in JavaScript

Contents
In this article, you will learn how to find text on a page in JavaScript.
Finding text on a page in JavaScript
Finding text on a page in JavaScript is a common task in web development. Here are some methods you can use to find text on a page:
Using the document.body.innerText property
The innerText property returns the text content of the page as a string. You can search for text on the page by using the indexOf() method to search the innerText string.
const searchText = 'example';
const pageText = document.body.innerText;
if (pageText.indexOf(searchText) !== -1) {
console.log(`Text found: ${searchText}`);
} else {
console.log(`Text not found: ${searchText}`);
}
In this example, we first retrieve the text content of the page using the innerText property of the document.body element. We then use the indexOf() method to search for the specified text, and log a message to the console depending on whether the text was found or not.
Using the document.querySelectorAll() method
The querySelectorAll() method returns a collection of elements that match a specified CSS selector. You can search for text on the page by selecting all elements that contain text using the *:contains() selector, and iterating over the collection to search for the specified text.
const searchText = 'example';
const elements = document.querySelectorAll('*:contains(' + searchText + ')');
if (elements.length > 0) {
console.log(`Text found: ${searchText}`);
} else {
console.log(`Text not found: ${searchText}`);
}
In this example, we use the querySelectorAll() method to select all elements that contain the specified text using the *:contains() selector. We then check the length of the resulting collection to determine if the text was found or not.
Using a regular expression
You can also use a regular expression to search for text on the page. The RegExp.prototype.test() method returns true if a match is found, and false otherwise.
const searchText = 'example';
const regex = new RegExp(searchText, 'gi');
const pageText = document.body.innerText;
if (regex.test(pageText)) {
console.log(`Text found: ${searchText}`);
} else {
console.log(`Text not found: ${searchText}`);
}
In this example, we create a regular expression object using the specified search text and the gi flags to perform a case-insensitive search. We then use the test() method to search the innerText string for a match, and log a message to the console depending on whether the text was found or not.
These methods can be used in combination with other JavaScript code to create more complex search functionality, such as highlighting or replacing matching text on the page. It is important to note that searching for text on a page can be resource-intensive, especially for large pages, so it is important to use these methods judiciously and optimize them for performance if necessary.