|
| 1 | +/** |
| 2 | + * Removes content wrapped in specified tags from a string |
| 3 | + * @param content The content string to process |
| 4 | + * @param tag The tag name without angle brackets (e.g., 'think' for '<think></think>') |
| 5 | + * @returns The content with the specified tags and their contents removed, and trimmed |
| 6 | + */ |
| 7 | +export function removeContentTags<T extends string | null | undefined>(content: T, tag: string): T { |
| 8 | + if (!content || typeof content !== 'string') { |
| 9 | + return content; |
| 10 | + } |
| 11 | + |
| 12 | + // Dynamic implementation for other cases |
| 13 | + const openTag = `<${tag}>`; |
| 14 | + const closeTag = `</${tag}>`; |
| 15 | + |
| 16 | + // Parse the content and remove tags |
| 17 | + let result = ''; |
| 18 | + let skipUntil: number | null = null; |
| 19 | + let depth = 0; |
| 20 | + |
| 21 | + for (let i = 0; i < content.length; i++) { |
| 22 | + // Check for opening tag |
| 23 | + if (content.substring(i, i + openTag.length) === openTag) { |
| 24 | + depth++; |
| 25 | + if (depth === 1) { |
| 26 | + skipUntil = content.indexOf(closeTag, i + openTag.length); |
| 27 | + i = i + openTag.length - 1; // Skip the opening tag |
| 28 | + continue; |
| 29 | + } |
| 30 | + } |
| 31 | + // Check for closing tag |
| 32 | + else if (content.substring(i, i + closeTag.length) === closeTag && depth > 0) { |
| 33 | + depth--; |
| 34 | + if (depth === 0) { |
| 35 | + i = i + closeTag.length - 1; // Skip the closing tag |
| 36 | + skipUntil = null; |
| 37 | + continue; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + // Only add character if not inside a tag |
| 42 | + if (skipUntil === null) { |
| 43 | + result += content[i]; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + // Normalize spaces (replace multiple spaces with a single space) |
| 48 | + result = result.replace(/\s+/g, ' ').trim(); |
| 49 | + |
| 50 | + return result as unknown as T; |
| 51 | +} |
0 commit comments