JavaScript Find Blank Lines

From Regex Regular Expression Encyclopedia

Jump to: navigation, search

You can use this recipe for identifying blank lines in a file. Blank lines can contain spaces or tabs, or they can contain a combination of spaces and tabs. Variations on these expressions can be useful for stripping blank lines from a file.

[edit] code

<html>
<head>
<title></title>
</head>
<body>
<form name="form1">
   <input type="textbox" name="txtInput" />
   <script type="text/javascript">
   function validate() {
       if (! document.form1.txtInput.value.match(/^\s*$/)) {
          alert("Please enter valid value!")
       } else {
          alert("Success!")
       }
   }
   </script>
   <input type="button" name="btnSubmit" onclick="validate()" value="Go" />
</form>
</body>
</html>

[edit] How It Works

This recipe uses a simple character class to limit the input to digits and the letters a through f:

Regular Expression Description
^ starts the beginning of the line, followed by . . .
\s any whitespace character (a tab or space) . . .
* zero or more times, followed by . . .
$ the end of the line.

[edit] How It Works

In addition to completely blank lines, this expression also matches lines that have only tabs or spaces in them. It does this by using the \s character class, which matches a tab or a space.

Here's the expression broken down into parts:

Personal tools