Reputation: 337
Let suppose I have a string:
var firstString = "<h3>askhaks</h3><h3>1212</h3><h1 style='color:red;
text-decoration:underline;'><a href=''><span id='123'><i class='fa fa-inr'></i>
</span> Hello! Admin</span></a></h1><p>This is the content of page 'String
Replace in Javascript'</p><h1>First</h1><span><h1>Hello! Admin</h1>Thank You for
visiting this page</span><h1>Third</h1>";
I want to change text of first <h1>
tag without losing all other inner tags i.e. <a href=''><span id='123'><i class='fa fa-inr'></i> </span>
Just want to replace Hello! Admin with another text. I am able to replace text of first <h1>
tag with the below code without losing the inline styling added to <h1>
but I am loosing the inner tags.
var innerText = document.getElementsByTagName('h1')[0].innerHTML;
How to achieve this?
Upvotes: 0
Views: 1541
Reputation: 568
If it’s not in the DOM and it’s a string you can use a regex in a replace like:
str.replace(“(<h1>)(.+)(<\/h1>)”, “$1YOUR_NEW_TEXT$2”);
Upvotes: 0
Reputation: 370679
If you want to change the text before inserting it into the document, you can use DOMParser
on the input HTML string, get its trimmed textContent
, and then replace
the substring in the input with your desired string, thus preserving all HTML tags:
var firstString = "<h3>askhaks</h3><h3>1212</h3><h1 style='color:red;text-decoration:underline;'><a href=''><span id='123'><i class='fa fa-inr'></i></span> Hello! Admin</span></a></h1><p>This is the content of page 'String Replace in Javascript'</p><h1>First</h1><span><h1>Second</h1>Thank You for visiting this page</span><h1>Third</h1>";
const doc = new DOMParser().parseFromString(firstString, 'text/html');
const h1Text = doc.querySelector('h1').textContent.trim();
console.log(firstString.replace(h1Text, 'foo bar new string'));
Upvotes: 3