I have a string, that may or may not be valid HTML, but it should contain a Title tag.
I want to replace the content of the title with new content.
Example 1:
lorem yada yada <title>Foo</title> ipsum yada yada
Should turn into:
lorem yada yada <title>Bar</title> ipsum yada yada
Example 2:
lorem yada yada <title attributeName="value">Foo</title> ipsum yada yada
Should turn into:
lorem yada yada <title attributeName="value">Bar</title> ipsum yada yada
I don’t want to parse html with regex – just replace the title tag… Please don’t send me here…
EDIT:
After numerous down votes and a lot of patronizing attitude –
I am aware (as admitted in the original post) that usually Regex is not the way to handle HTML. I am open to any solution that will solve my problem, but till now every JQuery / DOM solution did not work. Being “right” is not enough.
It’s difficult to do such a thing reliably with regex (read: “will not work for all cases”), thus using some kind of proper parser is best if possible.
That said, here is a simple expression that would work for your examples:
Some things that this does not handle and will not work right with: comments, quotes, CDATA, etc.