You really have to watch out with regex/.replace
approaches to this problem: it's easy to replace all kinds of text you don't want to touch.
An approach that could be a bit "safer":
- Locate the
<span>
you want to remove.
- Locate its parent element.
- Check if it is surrounded by text nodes (
nodeType == 3
)
- If there's a text node before the
<span>
you're removing, trim white space the end of its nodeValue
.
- If there's a text node after the element, trim white space at its start.
Still, I don't believe the way you're processing your HTML and stripping out stuff will be very future-proof... Small changes to the content will bring up new problems.
An example (written to be clear, not concise):
var spanToRemove = document.querySelector(".nestedSpan");
var spanParent = spanToRemove.parentElement;
var childNodes = spanParent.childNodes;
var childNodesArray = [];
for (var i = 0; i < childNodes.length; i += 1) {
childNodesArray.push(childNodes[i]);
}
var spanIndex = childNodesArray.indexOf(spanToRemove);
var textBefore = childNodes[spanIndex - 1];
var textAfter = childNodes[spanIndex + 1];
if (textBefore && textBefore.nodeType == 3) {
// Trims both ends, would be better to just trim right end
textBefore.nodeValue = textBefore.nodeValue.trim();
}
if (textAfter && textAfter.nodeType == 3) {
// Trims both ends, would be better to just trim left end
textAfter.nodeValue = textAfter.nodeValue.trim();
}
spanParent.removeChild(spanToRemove);
<p>Text before <span class="nestedSpan"> This gets removed </span> , Text after</p>