Skip to content

Commit

Permalink
Fix regex usage.
Browse files Browse the repository at this point in the history
  • Loading branch information
thesoftwarephilosopher committed Aug 17, 2024
1 parent e3124c0 commit a4c270f
Showing 1 changed file with 6 additions and 7 deletions.
13 changes: 6 additions & 7 deletions site/samples/sample4.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,13 @@ export default function FindNames() {

updateMatches();
function updateMatches() {
const regex = new RegExp(`(${input.value})`, 'gi');
const matched = (data.entries()
.filter(([k]) => k.match(input.value))
.filter(([k]) => k.match(regex))
.toArray());

const matches = (Iterator.from(matched)
.map(match => <Item regex={input.value} match={match} />)
.map(match => <Item regex={regex} match={match} />)
.take(30));

results.replaceChildren(...matches);
Expand All @@ -31,16 +32,14 @@ export default function FindNames() {
</div>;
}

function Item(attrs: { match: [string, number], regex: string }) {
function Item(attrs: { match: [string, number], regex: RegExp }) {
const [name, count] = attrs.match;
const total = <small style='color:#fff3'>({count})</small>;
return <li>
<span innerHTML={highlight(name, attrs.regex)} /> {total}
</li>;
}

function highlight(str: string, regex: string) {
if (!regex) return str;
const r = new RegExp(`(${regex})`, 'gi');
return str.replace(r, '<span class="match">$1</span>');
function highlight(str: string, regex: RegExp) {
return str.replace(regex, '<span class="match">$1</span>');
}

0 comments on commit a4c270f

Please sign in to comment.