JavaScript - Regex

From NoskeWiki
Jump to navigation Jump to search
Demonstration of interface


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.


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

  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;



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

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

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

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