signal-desktop/ts/util/getInitials.ts

32 lines
829 B
TypeScript
Raw Normal View History

2023-01-03 19:55:46 +00:00
// Copyright 2018 Signal Messenger, LLC
2020-10-30 20:34:04 +00:00
// SPDX-License-Identifier: AGPL-3.0-only
2019-01-14 21:49:58 +00:00
export function getInitials(name?: string): string | undefined {
if (!name) {
return undefined;
}
const parsedName = name
// remove all chars that are not letters or separators
.replace(/[^\p{L}\p{Z}]+/gu, '')
// replace all chars that are separators with a single ASCII space
.replace(/\p{Z}+/gu, ' ')
.trim();
if (!parsedName) {
return undefined;
}
// check if chars in the parsed string are initials
if (parsedName.length === 2 && parsedName === parsedName.toUpperCase()) {
return parsedName;
}
const parts = parsedName.toUpperCase().split(' ');
const partsLen = parts.length;
return partsLen === 1
? parts[0].charAt(0)
: parts[0].charAt(0) + parts[partsLen - 1].charAt(0);
}