-1

I am removing a <span> contained inside of a <p>. Sometimes there is a space before and after the <span>, which is causing an extra space when the <span> is stripped out. Note: I cannot change the HTML.

JSFiddle

$('span:contains("Name"),span:contains("name"),span:contains("[]"),span:contains("[ ]")').remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="item">Hi <span class="name">User Name</span> , I see you need...</p>

So I want to remove the space only if the span is removed.

RooksStrife
  • 1,647
  • 3
  • 22
  • 54
  • Duplicate: http://stackoverflow.com/questions/1981349/regex-to-replace-multiple-spaces-with-a-single-space – TylerH May 03 '16 at 16:14

4 Answers4

1

After you strip out the <span></span> do another selection for the <p></p> content and use this idea, string = string.replace(/ +/g, ' ');

Community
  • 1
  • 1
arodjabel
  • 420
  • 5
  • 14
0

Remove the space before and after the span. Put inside the span.

<p class="item">Hi<span class="name"> User Name </span>, I see you need...</p>

Will that work?

Cian W
  • 96
  • 1
  • 1
  • 10
0

replace the white space with nothing, like so:

var str = "Test One";
str = str.replace(/ /g, '');
TylerH
  • 20,799
  • 66
  • 75
  • 101
0

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>
user3297291
  • 22,592
  • 4
  • 29
  • 45