X Tutup
Skip to content

Allow user customization of regex used for matching emojis#146

Open
lionel-rowe wants to merge 2 commits intojdecked:mainfrom
lionel-rowe:customize-regex
Open

Allow user customization of regex used for matching emojis#146
lionel-rowe wants to merge 2 commits intojdecked:mainfrom
lionel-rowe:customize-regex

Conversation

@lionel-rowe
Copy link

Fixes #91... I think? Well anyway, it fulfils my use case, maybe @killroy42 can feedback as to whether it fulfils theirs. Notably, it always maps the matched emoji to the relevant icon file name, such that e.g. if "ABC" is matched as an emoji, it always becomes 41-42-43.png or 41-42-43.svg. Supplying custom mappings is not supported, but a future PR could build on this one to enable that if it's desirable.

Perf should remain near-identical for cases where the default regex is used, with a small performance hit in cases where a customized regex is supplied. This is due to the XSS-prevention logic, which is assumed unnecessary with the default regex.

Usage:

twemoji.regex = /[\p{RGI_Emoji}--💩]/gv // set to match all RGI emojis, except for poop emoji
twemoji.parse('🦄💩') // only "🦄" is parsed
twemoji.regex = twemoji.defaultRegex // reset
twemoji.parse('🦄💩') // now both are parsed again

// here "ABC" is also parsed as an emoji
twemoji.parse(
    'ABC🦄💩',
    { regex: new RegExp(`ABC|${twemoji.defaultRegex.source}`, 'g') },
)

// to prevent any XSS risk, "<>&'\"" are skipped over,
// even if the user-supplied regex would match them
twemoji.parse('<>&\'"!', { regex: /[<>&'"!]/g }) // only "!" is parsed

// just a private shortcut
fromCharCode = String.fromCharCode;

Object.defineProperties(twemoji, {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Object.defineProperties and Array#map used below are both IE9+. I only mention this as I noticed there's a comment about IE6 support, which I assume (maybe wrongly?) isn't needed any more in AD 2025. I've tried to be scrupulous about avoiding any other overly modern features (method syntax or arrow functions, trailing commas, new regex flags, etc.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add custom characters at runtime

1 participant

X Tutup