Barazo default frontend barazo.forum
at main 33 lines 1.0 kB view raw
1import { sanitize } from 'isomorphic-dompurify' 2 3/** 4 * Formats a bio string: escapes HTML, autolinks URLs, converts newlines to <br>, 5 * then sanitizes with DOMPurify (only <a> and <br> allowed). 6 */ 7export function formatBio(bio: string): string { 8 if (!bio) return '' 9 10 // Step 1: Escape HTML entities 11 let result = bio 12 .replace(/&/g, '&amp;') 13 .replace(/</g, '&lt;') 14 .replace(/>/g, '&gt;') 15 .replace(/"/g, '&quot;') 16 .replace(/'/g, '&#39;') 17 18 // Step 2: Autolink URLs (only http:// and https://) 19 // Display text strips protocol prefix and trailing slash for cleaner appearance. 20 result = result.replace(/https?:\/\/[^\s<]+/g, (url) => { 21 const display = url.replace(/^https?:\/\//, '').replace(/\/$/, '') 22 return `<a href="${url}" rel="noopener noreferrer">${display}</a>` 23 }) 24 25 // Step 3: Convert newlines to <br> 26 result = result.replace(/\n/g, '<br>') 27 28 // Step 4: Sanitize (only allow <a> and <br>) 29 return sanitize(result, { 30 ALLOWED_TAGS: ['a', 'br'], 31 ALLOWED_ATTR: ['href', 'rel'], 32 }) 33}