fix surrogate pair check in js

This commit is contained in:
Vitaly Turovsky 2025-04-26 05:51:00 +03:00
commit 305f4d8a31
2 changed files with 21 additions and 5 deletions

View file

@ -70,9 +70,15 @@ test('isAllowedChatCharacter', () => {
expect(isAllowedChatCharacter('a')).toBe(true)
expect(isAllowedChatCharacter('§')).toBe(false)
expect(isAllowedChatCharacter(' ')).toBe(true)
expect(isAllowedChatCharacter('ツ')).toBe(true)
expect(isStringAllowed('🟢')).toMatchObject({
expect(isStringAllowed('a§b')).toMatchObject({
valid: false,
clean: 'ab',
invalid: ['§']
})
expect(isStringAllowed('aツ')).toMatchObject({
valid: true,
})
expect(isStringAllowed('a🟢')).toMatchObject({
valid: true,
invalid: null
})
})

View file

@ -137,14 +137,24 @@ export function isAllowedChatCharacter (char: string): boolean {
export const isStringAllowed = (str: string) => {
const invalidChars = new Set<string>()
for (const char of str) {
for (const [i, char] of [...str].entries()) {
const isSurrogatePair = str.codePointAt(i) !== str['charCodeAt'](i)
if (isSurrogatePair) continue
if (!isAllowedChatCharacter(char)) {
invalidChars.add(char)
}
}
const valid = invalidChars.size === 0
if (valid) {
return {
valid: true
}
}
return {
valid: invalidChars.size === 0,
valid,
clean: [...str].filter(c => !invalidChars.has(c)).join(''),
invalid: [...invalidChars]
}