Find Text and Extract Context from a JavaScript String
1
min read .
Updated on
Sometimes a search result is more useful when it includes nearby text instead of returning only an index. A small helper can find a substring and return a configurable amount of context around it.
function findTextContext(text, query, context = 100) {
const index = text.indexOf(query);
if (index === -1) return null;
const start = Math.max(0, index - context);
const end = Math.min(text.length, index + query.length + context);
return text.slice(start, end);
}Example
const text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor.';
const result = findTextContext(text, 'consectetur', 20);
console.log(result);The helper finds the first occurrence and includes up to 20 characters before and after it.
Case-Insensitive Search
function findTextContextInsensitive(text, query, context = 100) {
const index = text.toLocaleLowerCase().indexOf(query.toLocaleLowerCase());
if (index === -1) return null;
return text.slice(
Math.max(0, index - context),
Math.min(text.length, index + query.length + context),
);
}For language-specific search, tokenization, stemming, fuzzy matching, or Unicode normalization, a dedicated search strategy may be more appropriate than simple substring matching.
Conclusion
Use indexOf() or search() to locate text, then slice() to return the surrounding context. Returning null for “not found” is usually easier for callers to distinguish from an actual text result than returning a magic string such as 'not found'.