mozilla

Revision 118298 of Examples of Regular Expressions

  • Revision slug: JavaScript/Guide/Obsolete_Pages/Working_with_Regular_Expressions/Examples_of_Regular_Expressions
  • Revision title: Examples of Regular Expressions
  • Revision id: 118298
  • Created:
  • Creator: Major Small
  • Is current revision? No
  • Comment more <noinclude>

Revision Content

Examples

The following examples show some uses of regular expressions.

Changing the Order in an Input String

The following example illustrates the formation of regular expressions and the use of string.split() and string.replace(). It cleans a roughly formatted input string containing names (first name first) separated by blanks, tabs and exactly one semicolon. Finally, it reverses the name order (last name first) and sorts the list.

<script type="text/javascript">

// The name string contains multiple spaces and tabs,
// and may have multiple spaces between first and last names.
var names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ; Chris Hand ";

var output = new Array(
  "---------- Original String<br><br>",
  names + "<br><br>");

// Prepare two regular expression patterns and array storage.
// Split the string into array elements.

// pattern: possible white space then semicolon then possible white space
var pattern = /\s*;\s*/;

// Break the string into pieces separated by the pattern above and
// and store the pieces in an array called nameList
var nameList = names.split(pattern);

// new pattern: one or more characters then spaces then characters.
// Use parentheses to "memorize" portions of the pattern.
// The memorized portions are referred to later.
var pattern = /(\w+)\s+(\w+)/;

// New array for holding names being processed.
var bySurnameList = new Array();

// Display the name array and populate the new array
// with comma-separated names, last first.
//
// The replace method removes anything matching the pattern
// and replaces it with the memorized string—second memorized portion
// followed by comma space followed by first memorized portion.
//
// The variables $1 and $2 refer to the portions
// memorized while matching the pattern.

output.push("---------- After Split by Regular Expression<BR>");

var i, len;
for (i = 0, len = nameList.length; i < len; i++)
{
  output.push(nameList[i] + "<br>");
  bySurnameList[i] = nameList[i].replace(pattern, "$2, $1")
}

// Display the new array.
output.push("---------- Names Reversed<br>");
for (i = 0, len = bySurnameList.length; i < len; i++)
{
  output.push(bySurnameList[i] + "<br>")
}

// Sort by last name, then display the sorted array.
bySurnameList.sort();
output.push("---------- Sorted<br>");
for (i = 0, len = bySurnameList.length; i < len; i++)
{
  output.push(bySurnameList[i] + "<br>")
}

output.push("---------- End<br>");

document.write(output.join("\n"));

</script>

Using Special Characters to Verify Input

In the following example, a user enters a phone number. When the user presses Enter, the script checks the validity of the number. If the number is valid (matches the character sequence specified by the regular expression), the script posts a window thanking the user and confirming the number. If the number is invalid, the script posts a window informing the user that the phone number is not valid.

The regular expression looks for zero or one open parenthesis \(?, followed by three digits \d{3}, followed by zero or one close parenthesis \)?, followed by one dash, forward slash, or decimal point and when found, remember the character ({{mediawiki.external('-\\/\\.')}}), followed by three digits \d{3}, followed by the remembered match of a dash, forward slash, or decimal point \1, followed by four digits \d{4}.

The Change event activated when the user presses Enter sets the value of RegExp.input.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <meta http-equiv="Content-Script-Type" content="text/javascript">
    <script type="text/javascript">
      var re = /\(?\d{3}\)?([-\/\.])\d{3}\1\d{4}/;

      function testInfo(phoneInput)
      {
        var OK = re.exec(phoneInput.value);

        if (!OK)
        {
          window.alert(RegExp.input + " isn't a phone number with area code!");
        }
        else
        {
          window.alert("Thanks, your phone number is " + OK[0]);
        }
      }
    </script>
  </head>

  <body>
    <p>Enter your phone number (with area code) and then press Enter.</p>
    <form action="">
      <input name="phone" onchange="testInfo(this);">
    </form>
  </body>
</html>

{{template.PreviousNext("Core_JavaScript_1.5_Guide:Working_with_Regular_Expressions:Executing_a_Global_Search%2C_Ignoring_Case%2C_and_Considering_Multiline_Input", "Core_JavaScript_1.5_Guide:Block_Statement")}}

{{ wiki.languages( { "fr": "fr/Guide_JavaScript_1.5/Travailler_avec_les_expressions_rationnelles/Exemples_d\'expressions_rationnelles", "ja": "ja/Core_JavaScript_1.5_Guide/Working_with_Regular_Expressions/Examples_of_Regular_Expressions", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Praca_z_wyra\u017ceniami_regularnymi/Przyk\u0142ady_wyra\u017ce\u0144_regularnych" } ) }}

Revision Source

<div class="noinclude"></div>
<h3 name="Examples"> Examples </h3>
<p>The following examples show some uses of regular expressions.
</p>
<h4 name="Changing_the_Order_in_an_Input_String"> Changing the Order in an Input String </h4>
<p>The following example illustrates the formation of regular expressions and the use of <code>string.split()</code> and <code>string.replace()</code>. It cleans a roughly formatted input string containing names (first name first) separated by blanks, tabs and exactly one semicolon. Finally, it reverses the name order (last name first) and sorts the list.
</p>
<pre>&lt;script type="text/javascript"&gt;

// The name string contains multiple spaces and tabs,
// and may have multiple spaces between first and last names.
var names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ; Chris Hand ";

var output = new Array(
  "---------- Original String&lt;br&gt;&lt;br&gt;",
  names + "&lt;br&gt;&lt;br&gt;");

// Prepare two regular expression patterns and array storage.
// Split the string into array elements.

// pattern: possible white space then semicolon then possible white space
var pattern = /\s*;\s*/;

// Break the string into pieces separated by the pattern above and
// and store the pieces in an array called nameList
var nameList = names.split(pattern);

// new pattern: one or more characters then spaces then characters.
// Use parentheses to "memorize" portions of the pattern.
// The memorized portions are referred to later.
var pattern = /(\w+)\s+(\w+)/;

// New array for holding names being processed.
var bySurnameList = new Array();

// Display the name array and populate the new array
// with comma-separated names, last first.
//
// The replace method removes anything matching the pattern
// and replaces it with the memorized string—second memorized portion
// followed by comma space followed by first memorized portion.
//
// The variables $1 and $2 refer to the portions
// memorized while matching the pattern.

output.push("---------- After Split by Regular Expression&lt;BR&gt;");

var i, len;
for (i = 0, len = nameList.length; i &lt; len; i++)
{
  output.push(nameList[i] + "&lt;br&gt;");
  bySurnameList[i] = nameList[i].replace(pattern, "$2, $1")
}

// Display the new array.
output.push("---------- Names Reversed&lt;br&gt;");
for (i = 0, len = bySurnameList.length; i &lt; len; i++)
{
  output.push(bySurnameList[i] + "&lt;br&gt;")
}

// Sort by last name, then display the sorted array.
bySurnameList.sort();
output.push("---------- Sorted&lt;br&gt;");
for (i = 0, len = bySurnameList.length; i &lt; len; i++)
{
  output.push(bySurnameList[i] + "&lt;br&gt;")
}

output.push("---------- End&lt;br&gt;");

document.write(output.join("\n"));

&lt;/script&gt;
</pre>
<h4 name="Using_Special_Characters_to_Verify_Input"> Using Special Characters to Verify Input </h4>
<p>In the following example, a user enters a phone number. When the user presses Enter, the script checks the validity of the number. If the number is valid (matches the character sequence specified by the regular expression), the script posts a window thanking the user and confirming the number. If the number is invalid, the script posts a window informing the user that the phone number is not valid.
</p><p>The regular expression looks for zero or one open parenthesis \(?, followed by three digits \d{3}, followed by zero or one close parenthesis \)?, followed by one dash, forward slash, or decimal point and when found, remember the character ({{mediawiki.external('-\\/\\.')}}), followed by three digits \d{3}, followed by the remembered match of a dash, forward slash, or decimal point \1, followed by four digits \d{4}.
</p><p>The <code>Change</code> event activated when the user presses Enter sets the value of <code>RegExp.input</code>.
</p>
<pre>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd"&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt;
    &lt;meta http-equiv="Content-Script-Type" content="text/javascript"&gt;
    &lt;script type="text/javascript"&gt;
      var re = /\(?\d{3}\)?([-\/\.])\d{3}\1\d{4}/;

      function testInfo(phoneInput)
      {
        var OK = re.exec(phoneInput.value);

        if (!OK)
        {
          window.alert(RegExp.input + " isn't a phone number with area code!");
        }
        else
        {
          window.alert("Thanks, your phone number is " + OK[0]);
        }
      }
    &lt;/script&gt;
  &lt;/head&gt;

  &lt;body&gt;
    &lt;p&gt;Enter your phone number (with area code) and then press Enter.&lt;/p&gt;
    &lt;form action=""&gt;
      &lt;input name="phone" onchange="testInfo(this);"&gt;
    &lt;/form&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre>
<div class="noinclude">
<p>{{template.PreviousNext("Core_JavaScript_1.5_Guide:Working_with_Regular_Expressions:Executing_a_Global_Search%2C_Ignoring_Case%2C_and_Considering_Multiline_Input", "Core_JavaScript_1.5_Guide:Block_Statement")}}
</p>
</div>
{{ wiki.languages( { "fr": "fr/Guide_JavaScript_1.5/Travailler_avec_les_expressions_rationnelles/Exemples_d\'expressions_rationnelles", "ja": "ja/Core_JavaScript_1.5_Guide/Working_with_Regular_Expressions/Examples_of_Regular_Expressions", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Praca_z_wyra\u017ceniami_regularnymi/Przyk\u0142ady_wyra\u017ce\u0144_regularnych" } ) }}
Revert to this revision