Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a specific tag content in javascript

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.

like image 452
seldary Avatar asked Jan 16 '23 08:01

seldary


2 Answers

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.

like image 135
Qtax Avatar answered Jan 18 '23 23:01

Qtax


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="/">"
like image 45
Esailija Avatar answered Jan 18 '23 22:01

Esailija