Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Find Text and Extract Context from a JavaScript String

1 min read .
Find Text and Extract Context from a JavaScript String

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.

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'.

Related Posts

chevron-up