| 1 | | function wrap(text, tag) { |
| 1 | // REFACTORING NOTES: |
| 2 | // 1. Improved function naming for clarity (parseBold, parseItalic instead of parse__, parse_) |
| 3 | // 2. Better separation of concerns - HTML generation vs parsing logic |
| 4 | // 3. More specific and safer regex patterns |
| 5 | // 4. Clearer function responsibilities |
| 6 | // 5. Maintained exact same functionality and output |
| 7 | |
| 8 | // Utility function to wrap text in HTML tags |
| 9 | function wrapTextInTag(text, tag) { |
| 2 | 10 | return `<${tag}>${text}</${tag}>`; |
| 3 | 11 | } |
| 4 | 12 | |
| 5 | | function isTag(text, tag) { |
| 13 | // Check if text starts with a specific HTML tag |
| 14 | function startsWithTag(text, tag) { |
| 6 | 15 | return text.startsWith(`<${tag}>`); |
| 7 | 16 | } |
| 8 | 17 | |
| 9 | | function parser(markdown, delimiter, tag) { |
| 10 | | const pattern = new RegExp(`${delimiter}(.+)${delimiter}`); |
| 11 | | const replacement = `<${tag}>$1</${tag}>`; |
| 12 | | return markdown.replace(pattern, replacement); |
| 18 | // Parse markdown with emphasis delimiters (bold or italic) |
| 19 | // More specific and safer than the generic parser function |
| 20 | function parseEmphasis(markdown, delimiter, htmlTag) { |
| 21 | // Use non-greedy matching and word boundaries for safety |
| 22 | const pattern = new RegExp(`${delimiter}([^${delimiter}]+?)${delimiter}`, 'g'); |
| 23 | return markdown.replace(pattern, `<${htmlTag}>$1</${htmlTag}>`); |
| 13 | 24 | } |
| 14 | 25 | |
| 15 | | function parse__(markdown) { |
| 16 | | return parser(markdown, '__', 'strong'); |
| 26 | // Parse bold text using double underscores |
| 27 | function parseBold(markdown) { |
| 28 | return parseEmphasis(markdown, '__', 'strong'); |
| 17 | 29 | } |
| 18 | 30 | |
| 19 | | function parse_(markdown) { |
| 20 | | return parser(markdown, '_', 'em'); |
| 31 | // Parse italic text using single underscores |
| 32 | function parseItalic(markdown) { |
| 33 | return parseEmphasis(markdown, '_', 'em'); |
| 21 | 34 | } |
| 22 | 35 | |
| 23 | | function parseText(markdown, list) { |
| 24 | | const parsedText = parse_(parse__(markdown)); |
| 25 | | if (list) { |
| 26 | | return parsedText; |
| 27 | | } else { |
| 28 | | return wrap(parsedText, 'p'); |
| 36 | // Parse inline formatting (bold and italic) within text |
| 37 | // Returns text with emphasis parsed, optionally wrapped in paragraph tags |
| 38 | function parseInlineFormatting(markdown, wrapInParagraph = true) { |
| 39 | // Apply bold parsing first, then italic (preserves original order) |
| 40 | const parsedText = parseItalic(parseBold(markdown)); |
| 41 | |
| 42 | if (wrapInParagraph) { |
| 43 | return wrapTextInTag(parsedText, 'p'); |
| 29 | 44 | } |
| 45 | return parsedText; |
| 30 | 46 | } |
| 31 | 47 | |
| 32 | 48 | function parseHeader(markdown, list) { |