JavaScript - Regex

From NoskeWiki
Jump to navigation Jump to search
Demonstration of interface

About

NOTE: This page is a daughter page of: JavaScript


Regex in JavaScript isn't too hard, but this can help. This example uses the line.match function to find matches in each line.

The HTML:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>JavaScript Regex Tester</title>

  <script>
  function PerformRegex() {
    var str = document.getElementById("my-text-area-in").value;
    var lines = str.split('\n');

    var outLines = '';
    for (var i = 0; i < lines.length; i++) {
      var line = lines[i];
      var found = line.match(/^\d{6,10}/g);  // Regex pattern to match.
      console.log(line + '    ->   ' + found)
      if (found) {
        outLines += found + '\n';
      }
    }
    document.getElementById("my-text-area-out").value = outLines;
  }
  </script>

</head>

<body>

  <textarea id="my-text-area-in" rows="4" cols="50">123456789 # someting
123456,something else

123456
</textarea><br/>
  <input type=button value="RunRegex" onclick="PerformRegex();">
  Regex using <code>line.match(/^\d{6,10}/g)</code>
  <br/>

  <textarea id="my-text-area-out" rows="4" cols="50"></textarea><br/>
</body>
</html>


Code license
For all of the code on my site... if there are specific instruction or licence comments please leave them in. If you copy my code with minimum modifications to another webpage, or into any code other people will see I would love an acknowledgment to my site.... otherwise, the license for this code is more-or-less WTFPL (do what you want)! If only copying <20 lines, then don't bother. That said - if you'd like to add a web-link to my site www.andrewnoske.com or (better yet) the specific page with code, that's a really sweet gestures! Links to the page may be useful to yourself or your users and helps increase traffic to my site. Hope my code is useful! :)



See Also