How to replace the contents of a specific tag with javascript

I have a string , which may or may not be valid HTML , but it should contain a Title tag.
I want to replace the content of the header 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 voices and a great patronizing attitude -
I know (as allowed in the original post) that usually Regex is not a way to handle HTML. I am open to any solution that solves my problem, but so far every jQuery / DOM solution has not worked. Being “right” is not enough.

+4
source share
3 answers

It is difficult to do such a thing reliably with a regular expression (read: “will not work for all cases”), so it’s best to use some kind of correct parser.

So here is a simple expression that will work for your examples:

 var re = /(<title\b[^>]*>)[^<>]*(<\/title>)/i; str = str.replace(re, "$1Bar$2"); 

Some things that this does not cope with and will not work correctly: comments, quotes, CDATA, etc.

+2
source
 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 . It makes no sense, but what happens.

Edit:

This seems to work in chrome (doesn't load images):

 var doc = document.implementation.createHTMLDocument(""); doc.body.innerHTML = "<img src='/'>"; doc.body.innerHTML; //"<img src="/">" 
+4
source

Please god, don’t try to parse html with a regular expression (I know you said you didn’t parse it, but you ...) jQuery has an absolutely nice set of html control primitives that is not in the DOM:

 var htmlishString = "almost <title>HTML</title>"; var $fakeDiv = jQuery('<div />'); $fakeDiv.html(htmlishString).find('title').text('Bar'); var manipulatedString = $fakeDiv.html() 

http://jsfiddle.net/4kQkx/

0
source

All Articles