Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Unreleased

- Drop support for Python 3.9.
- Remove previously deprecated code.
- Fix performance issue with ``striptags``. :issue:`521`


Version 3.0.3
Expand Down
39 changes: 22 additions & 17 deletions src/markupsafe/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,24 +204,29 @@ def striptags(self, /) -> str:
'Main » About'
"""
value = str(self)

# Look for comments then tags separately. Otherwise, a comment that
# contains a tag would end early, leaving some of the comment behind.

# keep finding comment start marks
while (start := value.find("<!--")) != -1:
# find a comment end mark beyond the start, otherwise stop
if (end := value.find("-->", start)) == -1:
break

value = f"{value[:start]}{value[end + 3 :]}"

# remove tags using the same method
while (start := value.find("<")) != -1:
if (end := value.find(">", start)) == -1:
parts = []
prev = 0
while True:
start = value.find("<", prev)
if start == -1:
break

value = f"{value[:start]}{value[end + 1 :]}"
if value[start : start + 4] == "<!--":
# comment
end = value.find("-->", start)
if end == -1:
break
parts.append(value[prev:start])
prev = end + 3
else:
# tag
end = value.find(">", start)
if end == -1:
break
parts.append(value[prev:start])
prev = end + 1
if prev > 0:
parts.append(value[prev:])
value = "".join(parts)

# collapse spaces
value = " ".join(value.split())
Expand Down
Loading