Skip to content

Commit 0fb0142

Browse files
authored
fix: mentioned user Regex parsing (#543)
If any of the characters .*+?^${}()|[\]\\ are included in the user.id token string, it's been modified to be properly parsed as a mentioned user.id format.
1 parent 9ec3605 commit 0fb0142

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

src/modules/Message/utils/tokens/__tests__/tokenizeUtils.spec.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,16 @@ describe('getUserMentionRegex', () => {
1818
const result = getUserMentionRegex(mentionedUsers, templatePrefix);
1919
expect(result).toEqual(/(@{1}|@{2})/g);
2020
});
21+
22+
it('should return a correct regex pattern; userId includes some patterns need to be escaped', () => {
23+
const mentionedUsers = [
24+
{ userId: '1*', nickname: 'user1' },
25+
{ userId: '2+', nickname: 'user2' },
26+
] as User[];
27+
const templatePrefix = '@';
28+
const result = getUserMentionRegex(mentionedUsers, templatePrefix);
29+
expect(result).toEqual(/(@{1\*}|@{2\+})/g);
30+
});
2131
});
2232

2333
describe('identifyMentions', () => {

src/modules/Message/utils/tokens/tokenize.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,14 @@ import { isUrl } from '../../../../utils';
55

66
export function getUserMentionRegex(mentionedUsers: User[], templatePrefix_: string): RegExp {
77
const templatePrefix = templatePrefix_ || USER_MENTION_PREFIX;
8-
return RegExp(`(${mentionedUsers.map(u => `${templatePrefix}{${u.userId}}`).join('|')})`, 'g');
8+
9+
return RegExp(`(${mentionedUsers.map(u => {
10+
const userId = u.userId.replace(
11+
// If user.id includes these patterns, need to convert it into an escaped one
12+
/([.*+?^${}()|[\]\\])/g,
13+
'\\$1');
14+
return `${templatePrefix}{${userId}}`;
15+
}).join('|')})`, 'g');
916
}
1017

1118
export function identifyMentions({
@@ -25,6 +32,7 @@ export function identifyMentions({
2532
}
2633
const { value } = token;
2734
const parts = value.split(userMentionRegex);
35+
2836
const tokens = parts.map((part) => {
2937
if (part.match(userMentionRegex)) {
3038
const matchedUser = mentionedUsers.find((user) => `@{${user?.userId}}` === part);

0 commit comments

Comments
 (0)