From 6f397ef7881a4965f2629eff57965567ee31d5d8 Mon Sep 17 00:00:00 2001 From: SnowCait Date: Thu, 6 Feb 2025 09:06:59 +0900 Subject: [PATCH] Fix parsing hashtags --- web/src/lib/Content.test.ts | 8 ++++++++ web/src/lib/Content.ts | 8 ++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/web/src/lib/Content.test.ts b/web/src/lib/Content.test.ts index bc142ca23..fd1ccedf8 100644 --- a/web/src/lib/Content.test.ts +++ b/web/src/lib/Content.test.ts @@ -29,6 +29,9 @@ describe('parse test', () => { expect(Content.parse('#nostter', [['t', 'nostter']])).toStrictEqual([ new Token('hashtag', '#nostter') ]); + expect(Content.parse('#nostter', [['t', '']])).toStrictEqual([ + new Token('text', '#nostter') + ]); }); it('emoji', () => { expect( @@ -88,6 +91,11 @@ describe('parse test', () => { new Token('url', 'https://example.com/') ]); }); + it('url in JSON', () => { + expect(Content.parse('{"key":"https://example.com/"}')).toStrictEqual([ + new Token('text', '{"key":"https://example.com/"}') + ]); + }); // it('url', () => { // expect(Content.parse('(https://example.com/path)')).toStrictEqual([ // new Token('text', '('), diff --git a/web/src/lib/Content.ts b/web/src/lib/Content.ts index f7ae30531..b367e1489 100644 --- a/web/src/lib/Content.ts +++ b/web/src/lib/Content.ts @@ -1,6 +1,7 @@ import { nip19 } from 'nostr-tools'; import type { EventPointer, ProfilePointer } from 'nostr-tools/lib/nip19'; import { unique } from './Array'; +import escapeStringRegexp from 'escape-string-regexp'; export class Token { constructor( @@ -14,7 +15,7 @@ export class Token { export class Content { static parse(content: string, tags: string[][] = []): Token[] { const hashtags = tags - .filter(([tagName, tagContent]) => tagName === 't' && tagContent !== undefined) + .filter(([tagName, tagContent]) => tagName === 't' && tagContent) .map(([, tagContent]) => tagContent); hashtags.sort((x, y) => y.length - x.length); const emojis = new Map( @@ -30,7 +31,10 @@ export class Content { matches = [ ...(hashtags.length > 0 ? content.matchAll( - new RegExp(`(${hashtags.map((x) => `#${x}`).join('|')})`, 'gi') + new RegExp( + `(${hashtags.map((x) => `#${escapeStringRegexp(x)}`).join('|')})`, + 'gi' + ) ) : []), ...(emojis.size > 0