【问题标题】:Remove white space form innerHTML string从 innerHTML 字符串中删除空格
【发布时间】:2021-05-30 00:17:05
【问题描述】:

我正在尝试删除标签前后的空白,以便我可以使用 JavaScript 获得干净的 HTML:

innerHTML 字符串(当我在控制台上打印时):

"
                    <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>

                "

在尝试以下操作时:

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

它会删除内部标签空白,但我只想删除标签前后的空白。

【问题讨论】:

  • 为什么不return html.trim();
  • @HereticMonkey - 虽然不在 OP 中,但 html.trim() 不会考虑多个外部元素(删除它们之间的空格)

标签: javascript


【解决方案1】:

这使用 DOM 来帮助对外部元素进行排序,同时保留内部标签。为了扩展您的示例,我在 incoming_html 字符串中添加了另一个外部标签,中间有空格。

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;
}
&lt;div id='testbed'&gt;&lt;/div&gt;

【讨论】:

  • Uncaught ReferenceError: set is not defined
  • @DanielSmith - 我更新了我的答案,应该注意这一点
  • 我还有一个 JS 问题,如果你能看看那里会很有帮助stackoverflow.com/questions/68737245/…
【解决方案2】:

你可以试试这个:

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);

【讨论】:

    猜你喜欢
    • 2011-09-21
    • 2017-11-20
    • 1970-01-01
    • 2012-03-25
    • 2012-09-05
    相关资源
    最近更新 更多