forked from mdn/yari
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatches-in-text.ts
66 lines (62 loc) · 2.1 KB
/
matches-in-text.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const ESCAPE_CHARS_RE = /[.*+?^${}()|[\]\\]/g;
export function* findMatchesInText(
needle,
haystack,
{ attribute = null } = {}
) {
// Need to remove any characters that can affect a regex if we're going
// use the string in a manually constructed regex.
const escaped = needle.replace(ESCAPE_CHARS_RE, "\\$&");
let rex;
if (attribute) {
rex = new RegExp(`${attribute}=['"](${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 + (attribute ? attribute.length + 2 : 0);
yield { line, column };
}
}
export function getFirstMatchInText(needle, haystack) {
const index = haystack.indexOf(needle);
const left = haystack.substring(0, index);
const line = left.split("\n").length;
const column = left.length - left.lastIndexOf("\n");
return { line, column };
}
export function replaceMatchingLinksInMarkdown(needle, haystack, replacement) {
// Need to remove any characters that can affect a regex if we're going
// use the string in a manually constructed regex.
const escaped = needle.replace(ESCAPE_CHARS_RE, "\\$&");
const rex = new RegExp(String.raw`\[([^\]]*)\]\((?:${escaped})\)`, "g");
return haystack.replace(rex, (_, p1) => {
return `[${p1}](${replacement})`;
});
}
export function replaceMatchesInText(
needle,
haystack,
replacement,
{ inAttribute = null, removeEntireAttribute = false }
) {
// Need to remove any characters that can affect a regex if we're going
// use the string in a manually constructed regex.
const escaped = needle.replace(ESCAPE_CHARS_RE, "\\$&");
let rex;
if (inAttribute) {
rex = new RegExp(`\\s*${inAttribute}=['"](${escaped})['"]`, "g");
} else {
rex = new RegExp(`(${escaped})`, "g");
}
return haystack.replace(rex, (match, p1) => {
if (removeEntireAttribute) {
return "";
}
return match.replace(p1, replacement);
});
}