( email: string, entity = 'User', )
| 81 | * generateNameFromEmail('x@test.com') // 'User abc123' (fallback for unusable) |
| 82 | */ |
| 83 | export const generateNameFromEmail = ( |
| 84 | email: string, |
| 85 | entity = 'User', |
| 86 | ): string => { |
| 87 | const fallbackName = `${entity} ${generateFallbackId()}`; |
| 88 | |
| 89 | if (!email || !email.includes('@')) { |
| 90 | return fallbackName; |
| 91 | } |
| 92 | |
| 93 | const localPart = email.split('@')[0]; |
| 94 | |
| 95 | // Replace common separators with spaces |
| 96 | const withSpaces = localPart.replace(/[._-]/g, ' '); |
| 97 | |
| 98 | // Remove any remaining non-alphanumeric characters except spaces |
| 99 | const cleaned = withSpaces.replace(/[^a-zA-Z0-9 ]/g, '').trim(); |
| 100 | |
| 101 | // If the cleaned result is too short or just numbers, use fallback |
| 102 | if (cleaned.length < 2 || /^\d+$/.test(cleaned)) { |
| 103 | return fallbackName; |
| 104 | } |
| 105 | |
| 106 | // Capitalize each word |
| 107 | const capitalized = cleaned |
| 108 | .split(' ') |
| 109 | .filter((word) => word.length > 0) |
| 110 | .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) |
| 111 | .join(' '); |
| 112 | |
| 113 | return capitalized || fallbackName; |
| 114 | }; |
| 115 | |
| 116 | /** |
| 117 | * Strips HTML tags from a string, returning plain text |
no test coverage detected