验证所见即所得的空格

Validate a WYSIWYG for empty whitespaces

我正在尝试使用正则表达式验证 WYSIWYG 编辑器,当它有空空格(输入键、空格)时,它会 return 我是真的。

混合空格和回车键的示例结果是:

<p>&nbsp; &nbsp;&nbsp; &nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp; &nbsp;</p>
<p>&nbsp;&nbsp;</p>
    ... 
(not that the line number of <p> tag is not fixed, it depends on how many enter key i press)

注:

  1. 有时 &nbsp; 标签之间有空格,有时则没有。
  2. <p> 标签的数量不固定,这取决于我按了多少回车键。

我需要得出上述标准的正则表达式,但我遇到了困难

  1. &nbsp; 标签
  2. 之间的开关空格
  3. 1 组或更多组 <p> 标签具有 &nbsp;

我自己试过的正则表达式:

/^<p>(&nbsp;)+(\t)*<\/p>$

我的分隔 <p> 标签的代码片段测试结果:

<p>&nbsp; &nbsp;&nbsp; &nbsp;</p> -> 不匹配

<p>&nbsp;</p> -> 匹配

<p>&nbsp; &nbsp;</p> -> 不匹配

<p>&nbsp;&nbsp;</p> -> 匹配

希望你想要这样的东西。 理解 replaceAll 正则表达式比添加更复杂的正则表达式要容易得多。 只需执行以下示例即可查看实际效果。

//Replace all prototype function
String.prototype.replaceAll = function(search, replacement) {
  var target = this;
  return target.replace(new RegExp(search, 'g'), replacement);
};

//A function to detect if the content is empty
function isContentEmpty(text) {

  text = text.replaceAll("&nbsp;", "").
  replaceAll(" ", "").
  replaceAll("<p>", "").
  replaceAll("</p>", "").trim();

  return (text.length == 0) ? true : false;

}

//Empty test
var emptyText = document.getElementById("empty").innerHTML;
console.log("Is [id = empty] content is empty: ", isContentEmpty(emptyText));

//Not empty test
var notEmptyText = document.getElementById("not-empty").innerHTML;
console.log("Is [id = not-empty] content is empty: ", isContentEmpty(notEmptyText));
<div id="empty">
  <p>&nbsp; &nbsp;&nbsp; &nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp; &nbsp;</p>
  <p>&nbsp;&nbsp;</p>
</div>



<div id="not-empty">
  <p>&nbsp; &nbsp;&nbsp; &nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp; content &nbsp;</p>
  <p>&nbsp;&nbsp;</p>
</div>