Skip to content

Commit ac1bf36

Browse files
author
Chuanqi Sun
committed
Refactor RegExp pattern matcher
1 parent 3e24a08 commit ac1bf36

File tree

4 files changed

+12
-8
lines changed

4 files changed

+12
-8
lines changed

src/lib/utils/markdown.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { escapeRegExp } from "./regexp";
2+
3+
export function getEntryPatternByHref(href: string): RegExp {
4+
const existingItemPattern = String.raw`^- \[.+\]\(${escapeRegExp(href)}\).*$`;
5+
return new RegExp(existingItemPattern, "m");
6+
}

src/lib/utils/merge-content.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
1-
import { escapeRegExp } from "./regexp";
1+
import { getEntryPatternByHref } from "./markdown";
22

33
export function mergeContent(newEntryHref: string, newEntry: string, existinContent: string): string {
4-
const existingItemPattern = String.raw`^- \[.+\]\(${escapeRegExp(newEntryHref)}\).*$`;
5-
const replaceResult = existinContent.replace(new RegExp(existingItemPattern, "m"), newEntry);
4+
const replaceResult = existinContent.replace(getEntryPatternByHref(newEntryHref), newEntry);
65
return replaceResult === existinContent ? `${newEntry}\n${existinContent}` : replaceResult;
76
}

src/lib/utils/regexp.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
// ref: https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
2-
export function escapeRegExp(string) {
3-
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
2+
export function escapeRegExp(input: string) {
3+
return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
44
}

src/popup/view.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { fitTextareaToContent } from "../lib/utils/fit-textarea-to-content";
2-
import { escapeRegExp } from "../lib/utils/regexp";
2+
import { getEntryPatternByHref } from "../lib/utils/markdown";
33
import type { FullModel } from "./model";
44

55
const $ = document.querySelector.bind(document);
@@ -101,8 +101,7 @@ export class View {
101101
}
102102

103103
if (href !== previousState.href || markdownString !== previousState.markdownString) {
104-
const existingItemPattern = String.raw`^- \[.+\]\(${escapeRegExp(href)}\).*$`;
105-
const isExistingUrl = markdownString?.match(new RegExp(existingItemPattern, "m"));
104+
const isExistingUrl = markdownString?.match(getEntryPatternByHref(href!));
106105
existingLinkMarker.hidden = !isExistingUrl;
107106
}
108107

0 commit comments

Comments
 (0)