Ask Your Question
3

What is the method for eliminating HTML tags from a string while preserving line breaks?

asked 2022-06-16 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-06-12 22:00:00 +0000

devzero gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-06-16 11:00:00 +0000

Seen: 7 times

Last updated: Jun 12 '22