Your translation script changes href="/help" into a translated phrase, splits “Read the shipping policy” around an inline link, and mangles {{ first_name }} . The common cause is treating HTML as text with boundaries a regular expression can recognize reliably. It cannot: attribute values, script content, and text between inline elements all have different structural roles.
Problem
Consider a shortcut that translates text inside quotation marks:
html = re . sub ( r '"([^"]+)"' , translate , html )
Enter fullscreen mode
Exit fullscreen mode
That expression has no way to tell whether a quoted string is an accessible label, a URL, a class name, a JavaScript value, or part of a template expression. A different pattern that targets text between tags has the opposite problem: inline markup divides a sentence into multiple matches. The phrase in <p>Read the <a href="/help">shipping policy</a> before ordering.</p> is not one uninterrupted text string in the source.…