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:
var re = /(<title\b[^>]*>)[^<>]*(<\/title>)/i;
str = str.replace(re, "$1Bar$2");
Some things that this does not handle and will not work right with: comments, quotes, CDATA, etc.
function replaceTitle( str, replacement ) {
var tmp = document.createElement("ihatechrome");
tmp.innerHTML = str;
tmp.getElementsByTagName("title")[0].innerHTML = replacement;
return tmp.innerHTML;
}
replaceTitle( "lorem yada yada <title>Foo</title> ipsum yada yada", "Bar" );
//"lorem yada yada <title>Bar</title> ipsum yada yada"
For some reason, google chrome makes requests if there are img
tags with src
. Doesn't make any sense but that's what happens.
Edit:
This seems to work in chrome (does not load images):
var doc = document.implementation.createHTMLDocument("");
doc.body.innerHTML = "<img src='/'>";
doc.body.innerHTML; //"<img src="/">"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With