-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
emotes.js
66 lines (53 loc) · 1.63 KB
/
emotes.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const emoji = require( 'emoji-regex' )();
module.exports = {
parseEmotes,
}
const whitespaceRegex = module.exports.whitespaceRegex = /\s+/g
const doubleColonRegex = /:(\w|-|\+)+:/g
// regex creation
const emoteRegexMap = new Map()
const regexChar = /\[|\\|\^|\$|\.|\||\?|\*|\+|\(|\)/g
const escapeChar = char => '\\' + char
const startBound = '(^|\\b|\\s)'
const endBound = '($|\\b|\\s)'
function parseEmotes( emotes, message ) {
let parsed = message;
for( var emoteID in emotes ) {
if( !emotes.hasOwnProperty( emoteID ) ) return
let regex = emoteRegexMap.get( emoteID )
if( !regex ) {
let [ start, end ] = emotes[ emoteID ][ 0 ]
.split( '-' )
.map( Number );
end++
if( start === 0 && end === message.length ) {
return ''
}
let emoteText = message.substring( start, end )
.replace( regexChar, escapeChar )
try {
regex = new RegExp( startBound + emoteText + endBound, 'g' );
} catch( e ) {
console.log( 'Exception on emote: ', emoteText, ': ', e );
/**
* If there was an exception, don't try to use an non-existant regex
*/
continue;
}
emoteRegexMap.set( emoteID, regex )
}
/*
* Because the regexes match against bounding whitespace,
* a whitespace character needs to be inserted
* to prevent words from being falsely concatenated.
* But will be tidied up before returning.
*/
parsed = parsed.replace( regex, ' ' );
}
parsed = parsed
.replace( doubleColonRegex, '' )
.replace( emoji, '' )
.replace( whitespaceRegex, ' ' )
.trim();
return parsed
}