UNPKG

2.02 kBJavaScriptView Raw
1import emojiRegexFactory from 'emoji-regex';
2
3/**
4 * Split the given string after each occurrence of each of the given symbols.
5 *
6 * Symbols are strings, and can be of length one or more. Zero-length symbols
7 * are ignored.
8 *
9 * Unlike with `String::split`, the symbol is left in results, with
10 * the split occurring _after_ the symbol.
11 *
12 * For example:
13 *
14 * splitAfterSymbols(['/'], 'a/b/c') // ['a/', 'b/', 'c']
15 * splitAfterSymbols(['foo'], 'foobar') // ['foo', 'bar']
16 *
17 * @param {string[]} symbols The symbols to split the string by.
18 * @param {string} string The string to split.
19 * @returns {string[]} The resulting strings.
20 */
21export const splitAfterSymbols = (symbols, string) => {
22 const textParts = [];
23 let textPartStartIndex = 0;
24
25 if (string.length === 0) {
26 return [string];
27 }
28
29 for (let i = 0; i < string.length; ) {
30 let symbolFound = false;
31
32 for (let j = 0; j < symbols.length; j += 1) {
33 const symbol = symbols[j];
34
35 if (!symbol) {
36 // eslint-disable-next-line no-continue
37 continue;
38 }
39
40 symbolFound = string.slice(i, i + symbol.length) === symbol;
41
42 if (symbolFound) {
43 const textPartEndIndex = i + symbol.length;
44 const textPart = string.slice(textPartStartIndex, textPartEndIndex);
45 textParts.push(textPart);
46 textPartStartIndex = textPartEndIndex;
47 i = textPartStartIndex;
48 break;
49 }
50 }
51
52 if (!symbolFound) {
53 i += 1;
54 }
55 }
56
57 const final = string.slice(textPartStartIndex);
58 if (final) {
59 textParts.push(final);
60 }
61
62 return textParts;
63};
64
65const startsWithEmojiRegex = `^(${emojiRegexFactory().source})`;
66
67export const getAvatarChar = (name) => {
68 if (name) {
69 // Check if string starts with an emoji (which could be multiple characters and zero-width joined)
70 const match = name.match(startsWithEmojiRegex);
71 if (match) {
72 // Return the first match
73 return match[0];
74 }
75 return name.charAt(0).toUpperCase();
76 }
77
78 return '';
79};