I'd use the DOMParser
to make sure we're doing some "smart" searching. Let's say you are looking for texts about the word "viewport"; you don't want any HTML file that has the <meta>
tag "viewport" to return as a valid result, would you?
Step one is parsing the string to a Document instance:
const parseHTMLString = (() => {
const parser = new DOMParser();
return str => parser.parseFromString(str, "text/html");
})();
Put a valid HTML string in here, and you'll get a document in return that behaves just like window.document
! This means we can do all kinds of cool stuff like using querySelector
and properties like innerText
.
The next step is to define what we want to search. Here's an example that joins in a document's title and body text:
const getSearchStringForDoc = doc => {
return [ doc.title, doc.body.innerText ]
.map(str => str.toLowerCase().trim())
.join(" ");
};
Pass your parsed document to this function, and you'll get a plain string in return that features just content, without attributes, tag names and meta data.
Now, it's a matter of defining the right search method. Could be a RegExp based match, or just a (less fast) split
& includes
:
const stringMatchesQuery = (str, query) => {
return query
.toLowerCase()
.split(/\W+/)
.some(q => str.includes(q))
};
Chain those methods together and you got the conversion like:
String -> Document -> String -> Boolean
If you ever want to include more information in the search content, you just update the getSearchStringForDoc
function using the standardized API.
A running example (that's a bit messy and could do with some refactoring, but hopefully gets the point across):
const htmlString = (
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>The title</title>
</head>
<body>
Some text about an interesting thing.
</body>
</html>`);
const parseHTMLString = (() => {
const parser = new DOMParser();
return str => parser.parseFromString(str, "text/html");
})();
const getSearchStringForDoc = doc => {
return [
doc.title,
doc.body.innerText
].map(str => str.trim())
.join(" ");
};
const stringMatchesQuery = (str, query) => {
str = str.toLowerCase();
query = query.toLowerCase();
return query
.split(/\W+/)
.some(q => str.includes(q))
};
const htmlStringMatchesQuery = (str, query) => {
const htmlDoc = parseHTMLString(str);
const htmlSearchString = getSearchStringForDoc(htmlDoc);
return stringMatchesQuery(htmlSearchString, query);
};
console.log("Match 'viewport':", htmlStringMatchesQuery(htmlString, "viewport"));
console.log("Match 'Interesting':", htmlStringMatchesQuery(htmlString, "Interesting"));