Daniel Smith
Daniel Smith

Reputation: 1734

Remove white space form innerHTML string

I'm trying to remove white space before and after tags so that I can get the clean HTML using JavaScript:

innerHTML String (while I print on console):

"
                    <p>There are <i>many variations </i>of passages of <b>Lorem</b> Ipsum available, but the majority have suffered alteration in some formThere are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form.</p>

                "

While trying with following:

function htmlCleanUp(html) {
        if (html) {
            return html.replace(/>\s+|\s+</g, function (m) {
                return m.trim();
            });
        }
    }

It removes inner tag white space, but I want to remove white space only before and after the tag.

Upvotes: 1

Views: 1198

Answers (2)

Kinglish
Kinglish

Reputation: 23654

This uses the DOM to help sort through outer elements while leaving the inner tags alone. To extend your example, I added another outer tag to the incoming_html string with spaces in between.

let incoming_html = "                                       <p>There are <i>many variations </i>of passages of <b>Lorem</b> Ipsum available, but the majority have suffered alteration in some formThere are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form.</p>       <div>another passage</div> ";


function htmlCleanUp(html) {
  console.log("Before transformation:", html);
  const testbed = document.getElementById('testbed');
  testbed.innerHTML = html;
  let sets = document.querySelectorAll("#testbed > *")
  let out = [];
  for (let set in sets) {
    out.push(sets[set].outerHTML)
  }
  testbed.innerHTML = "";
  return out.join("").trim();
}


console.log("After transformation:", htmlCleanUp(incoming_html));
#testbed {
  visible: hidden;
  height: 0;
  position: absolute;
  z-index: -1;
}
<div id='testbed'></div>

Upvotes: 1

tiagofga
tiagofga

Reputation: 60

You can try this:

const regex = /\s*<\s*/gm;
const str = ` <p>There are <i>many variations </i>of passage`;
const subst = `<`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

const regex2 = /\s*>s*/gm;
const subst2 = `>`;

// The substituted value will be contained in the result variable
const result2 = result.replace(regex2, subst2);
console.log('Substitution result: ', result2);

Upvotes: 2

Related Questions