Reputation: 6256
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.
Upvotes: 5
Views: 15254
Reputation: 28099
Please god don't try and parse html with a regex (I know you said you aren't parsing it, but you are...) jQuery has a perfectly good set of primitives to manipulate html that isn't in the DOM:
var htmlishString = "almost <title>HTML</title>";
var $fakeDiv = jQuery('<div />');
$fakeDiv.html(htmlishString).find('title').text('Bar');
var manipulatedString = $fakeDiv.html()
Upvotes: 0
Reputation: 140230
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="/">"
Upvotes: 4
Reputation: 33908
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.
Upvotes: 5