* Apply a text content change to an element.
(html: string, elementId: string, value: string)
| 377 | * Apply a text content change to an element. |
| 378 | */ |
| 379 | function patchTextContent(html: string, elementId: string, value: string): string { |
| 380 | const openTagPattern = new RegExp( |
| 381 | `(<([a-z0-9-]+)[^>]*\\bid=(["'])${escapeRegex(elementId)}\\3[^>]*>)`, |
| 382 | "i", |
| 383 | ); |
| 384 | const match = openTagPattern.exec(html); |
| 385 | if (!match || match.index == null) return html; |
| 386 | |
| 387 | const openingTag = match[1]; |
| 388 | const tagName = match[2]; |
| 389 | const contentStart = match.index + openingTag.length; |
| 390 | const closingIndex = findMatchingClosingTagIndex(html, tagName, contentStart); |
| 391 | if (closingIndex < 0) return html; |
| 392 | |
| 393 | return `${html.slice(0, contentStart)}${value}${html.slice(closingIndex)}`; |
| 394 | } |
| 395 | |
| 396 | function findMatchingClosingTagIndex(html: string, tagName: string, contentStart: number): number { |
| 397 | const tagPattern = new RegExp(`</?${escapeRegex(tagName)}\\b[^>]*>`, "gi"); |
no test coverage detected