Skip to content

Instantly share code, notes, and snippets.

@peterbe
Last active January 25, 2022 19:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterbe/a210437cd282ef0963749520f6b09a1c to your computer and use it in GitHub Desktop.
Save peterbe/a210437cd282ef0963749520f6b09a1c to your computer and use it in GitHub Desktop.
function* findMatchesInText(needle, haystack, { inQuotes = false } = {}) {
const escaped = needle.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
let rex;
if (inQuotes) {
rex = new RegExp(`['"](${escaped})['"]`, "g");
} else {
rex = new RegExp(`(${escaped})`, "g");
}
for (const match of haystack.matchAll(rex)) {
const left = haystack.slice(0, match.index);
const line = (left.match(/\n/g) || []).length + 1;
const lastIndexOf = left.lastIndexOf("\n") + 1;
const column = match.index - lastIndexOf + 1;
yield { line, column };
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment