Suppose that one has:
- an element object
element. - a regular expression or a simple string
pattern. - a string
replacement(this can be a simple string or one with replacement tokens).
In JavaScript, without invoking jQuery or a JavaScript library, how can one safely replace all of the occurrences of pattern with replacement in the child text nodes of element? How can one achieve this if replacement also contains markup instead of text that will be escaped if it contains less-than signs or greater-than signs? The problem with using element.innerHTML = element.innerHTML.replace(pattern, replacement) is that it can potentially break markup. So, using that to replace a hyperlink's displayed text could change the address the hyperlink points to.
The answer can contain can contain two solutions: one that replaces text with text (i.e., "<" in replacement would be treated as <) and one that replaces text with literal of the string (i.e., <br/> in replacement would be treated as <br/> instead of <br/>). Alternatively, the answer may contain only one solution that, like the second solution in the first option, treats < and > as < and >, respectively.