Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to eliminate HTML tags from a string while preserving line breaks is to use a regular expression to replace all HTML tags with an empty string, and then replace all occurrences of "\n" (newline character) with "
" (HTML line break tag). Here is an example implementation in Python:

import re

def remove_html_tags(text):
    # remove HTML tags
    text = re.sub(r'<[^>]+>', '', text)
    # replace newlines with HTML line break tag
    text = text.replace('\n', '<br>')
    return text

Example usage:

text = "<p>Hello, <b>world</b>!\nHow are you?</p>"
print(remove_html_tags(text))
# Output: Hello, world!<br>How are you?

Note that this method may not be perfect and might not work correctly for all HTML inputs. It's recommended to test it thoroughly and possibly adjust the regular expression to handle edge cases specific to your use case.