0

I'd like to replace some text in a string that represents a div tag that may or may not also include style and class attributes. For example,

var s = "<div style='xxx' class='xxx'>replaceThisText<div>

If it were just the tag, I believe I could just do this:

str = str.replace(/<div>[\s\S]*?<\/div>/, '<div>' + newText+ '<\/div>');

But how do I take the attributes into account?

2

2 Answers 2

2

Generate a temporary element with your string as HTML content then get the div within it to update content after updating the content get back the HTML of temporary element.

var s = "<div style='xxx' class='xxx'>replaceThisText<div>";

// create a temporary div element
var temp = document.createElement('div');

// set content as string
temp.innerHTML = s;

// get div within the temporary element
// and update the content within the div
temp.querySelector('div').innerHTML = 'newText';

// get back the current HTML content in the
// temporary div element
console.log(temp.innerHTML)

Why not regex?

RegEx match open tags except XHTML self-contained tags

Using regular expressions to parse HTML: why not?

Sign up to request clarification or add additional context in comments.

2 Comments

What about temp.firstChild.innerHTML='newText' other than using a querySelector?
@SpencerWieczorek : that's also fine if there is no leading whitespace or text in the content... otherwise it may be textNode
0

Regex will never be a good decision to parse html content.
Consider the following short solution using DOMParser object(for browsers which support DOMParser implementation, see compatibility table):

var s = "<div style='xxx' class='xxx'>replaceThisText<div>",
    tag = (new DOMParser()).parseFromString(s, 'text/html').querySelector('.xxx');

tag.textContent = 'newText';  // replacing with a new text
console.log(tag.outerHTML);   // outputs the initial tag representation with replaced content

https://developer.mozilla.org/ru/docs/Web/API/DOMParser

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.