Search code examples
javascriptregexwysiwyg

Validate a WYSIWYG for empty whitespaces


I am trying to validate a WYSIWYG editor using regular expression, when it has empty whitespaces (enter key, spaces), it will return me true.

The example outcome of a mixed spaces and enter key is:

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

Note:

  1. Sometime there are spaces between the &nbsp; tag, sometime not.
  2. Number of <p> tags is not fixed, it depends on how many enter key i press.

I need to come out a regex of the mentioned criteria, but i facing difficulties where

  1. The on-and-off spaces between &nbsp; tag
  2. 1 or more group of <p> tag that has &nbsp;

The regex i tried on my own:

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

My code snippet test result for separated <p> tags:

<p>&nbsp; &nbsp;&nbsp; &nbsp;</p> -> not matched

<p>&nbsp;</p> -> matched

<p>&nbsp; &nbsp;</p> -> not matched

<p>&nbsp;&nbsp;</p> -> matched


Solution

  • Hope you want something like this. It is much more easier to understand a replaceAll regex rather than adding a more complex one. Just execute the following example to see it in action.

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