JavaScript DHTML/Development/Regular Expressions

Материал из Web эксперт
Версия от 07:19, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

check Date format

   
<!-- 
     Example File From "JavaScript and DHTML Cookbook"
     Published by O"Reilly & Associates
     Copyright 2003 Danny Goodman
-->
function checkDate(fld) {
    var mo, day, yr;
    var entry = fld.value;
    var re = /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/;
    if (re.test(entry)) {
        var delimChar = (entry.indexOf("/") != -1) ? "/" : "-";
        var delim1 = entry.indexOf(delimChar);
        var delim2 = entry.lastIndexOf(delimChar);
        mo = parseInt(entry.substring(0, delim1), 10);
        day = parseInt(entry.substring(delim1+1, delim2), 10);
        yr = parseInt(entry.substring(delim2+1), 10);
        var testDate = new Date(yr, mo-1, day);
        alert(testDate)
        if (testDate.getDate() == day) {
            if (testDate.getMonth() + 1 == mo) {
                if (testDate.getFullYear() == yr) {
                    return true;
                } else {
                    alert("There is a problem with the year entry.");
                }
            } else {
                alert("There is a problem with the month entry.");
            }
        } else {
            alert("There is a problem with the date entry.");
        }
    } else {
        alert("Incorrect date format. Enter as mm/dd/yyyy.");
    }
    return false;
}
function validateDate(fld) {
    if (!checkDate(fld)) {
        // focus if validation fails
        fld.focus();
        fld.select();
    }
}
----------
function checkDate(fld) {
    var mo, day, yr;
    var entry = fld.value;
    var reLong = /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/;
    var reShort = /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{2}\b/;
    var valid = (reLong.test(entry)) || (reShort.test(entry));
    if (valid) {
        var delimChar = (entry.indexOf("/") != -1) ? "/" : "-";
        var delim1 = entry.indexOf(delimChar);
        var delim2 = entry.lastIndexOf(delimChar);
        mo = parseInt(entry.substring(0, delim1), 10);
        day = parseInt(entry.substring(delim1+1, delim2), 10);
        yr = parseInt(entry.substring(delim2+1), 10);
        // handle two-digit year
        if (yr < 100) {
            var today = new Date();
            // get current century floor (e.g., 2000)
            var currCent = parseInt(today.getFullYear() / 100) * 100;
            // two digits up to this year + 15 expands to current century
            var threshold = (today.getFullYear() + 15) - currCent;
            if (yr > threshold) {
                yr += currCent - 100;
            } else {
                yr += currCent;
            }
        }
        var testDate = new Date(yr, mo-1, day);
        if (testDate.getDate() == day) {
            if (testDate.getMonth() + 1 == mo) {
                if (testDate.getFullYear() == yr) {
                    // fill field with database-friendly format
                    fld.value = mo + "/" + day + "/" + yr;
                    return true;
                } else {
                    alert("There is a problem with the year entry.");
                }
            } else {
                alert("There is a problem with the month entry.");
            }
        } else {
            alert("There is a problem with the date entry.");
        }
    } else {
        alert("Incorrect date format. Enter as mm/dd/yyyy.");
    }
    return false;
}



Finding a substring within a string

   

<html>
  <head>
    <title>Finding a substring within a string</title>
    <script type="text/javascript">
        var a = "This is a test.";
        var b = a.indexOf("is");
        
        document.write(b);    
    </script>
  </head>
  <body>
  </body>
</html>



Regular Expression Match Workshop

   
/*
JavaScript Bible, Fourth Edition
by Danny Goodman 
Publisher: John Wiley & Sons CopyRight 2001
ISBN: 0764533428
*/
<HTML>
<HEAD>
<TITLE>Regular Expression Match</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function doMatch(form) {
    var str = form.entry.value
    var delim = (form.caseSens.checked) ? "/g" : "/gi"
    var regexp = eval("/" + form.regexp.value + delim)
    var resultArray = str.match(regexp)
    if (resultArray) {
        form.result.value = resultArray.toString()
        form.count.value = resultArray.length
    } else {
        form.result.value = "<no matches>"
        form.count.value = ""
    }
}
</SCRIPT>
</HEAD>
<BODY>
<B>String Match with Regular Expressions</B>
<HR>
<FORM>
Enter a main string:<INPUT TYPE="text" NAME="entry" SIZE=60
  VALUE="Many a maN and womAN have meant to visit GerMAny."><BR>
Enter a regular expression to match:<INPUT TYPE="text" NAME="regexp" SIZE=25
  VALUE="\wa\w">
<INPUT TYPE="checkbox" NAME="caseSens">Case-sensitive<P>
<INPUT TYPE="button" VALUE="Execute match()" onClick="doMatch(this.form)">
<INPUT TYPE="reset"><P>
Result:<INPUT TYPE="text" NAME="result" SIZE=40><BR>
Count:<INPUT TYPE="text" NAME="count" SIZE=3><BR>
</FORM>
</BODY>
</HTML>



Regular Expressions: Extracting Data from a Match

   
/*
JavaScript Bible, Fourth Edition
by Danny Goodman 
John Wiley & Sons CopyRight 2001
*/

<HTML>
<HEAD>
<TITLE>Got a Match?</TITLE>
<SCRIPT LANGUAGE="JavaScript1.2">
function extractIt(form) {
    var months = ["January","February","March","April","May","June","July",
"August","September","October","November","December"]
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
    var re = /\b(1[0-2]|0?[1-9])[\-\/](0?[1-9]|[12][0-9]|3[01])[\-\/]((19|20)\d{2})/
    var input = form.entry.value
    var matchArray = re.exec(input)
    if (matchArray) {
        var theMonth = months[matchArray[1] - 1] + " "
        var theDate = matchArray[2] + ", "
        var theYear = matchArray[3]
        var dateObj = new Date(matchArray[3],matchArray[1]-1,matchArray[2])
        var theDay = days[dateObj.getDay()] + " "
        form.output.value = theDay + theMonth + theDate + theYear
    } else {
        form.output.value = "An invalid date."
    }
}
</SCRIPT>
</HEAD>
<BODY>
<B>Use a regular expression to extract data from a string:</B>
<HR>
<FORM>
Enter a date in the format mm/dd/yyyy or mm-dd-yyyy:<BR>
<INPUT TYPE="text" NAME="entry" SIZE=12><P>
<INPUT TYPE="button" VALUE="Extract Date Components" onClick="extractIt(this.form)"><P>
The date you entered was:<BR>
<INPUT TYPE="text" NAME="output" SIZE=40><P>
<INPUT TYPE="reset">
</FORM>
</BODY>
</HTML>



Regular Expressions: Looking for a Match

   
/*
JavaScript Bible, Fourth Edition
by Danny Goodman 
John Wiley & Sons CopyRight 2001
*/
<HTML>
<HEAD>
<TITLE>Got a Match?</TITLE>
<SCRIPT LANGUAGE="JavaScript1.2">
function findIt(form) {
    var re = new RegExp(form.regexp.value)
    var input = form.main.value
    if (input.search(re) != -1) {
        form.output[0].checked = true
    } else {
        form.output[1].checked = true
    }
}
function locateIt(form) {
    var re = new RegExp(form.regexp.value)
    var input = form.main.value
    form.offset.value = input.search(re)
}
</SCRIPT>
</HEAD>
<BODY>
<B>Use a regular expression to test for the existence of a string:</B>
<HR>
<FORM>
Enter some text to be searched:<BR>
<TEXTAREA NAME="main" COLS=40 ROWS=4 WRAP="virtual">
The most famous ZIP code on Earth may be 90210.
</TEXTAREA><BR>
Enter a regular expression to search:<BR>
<INPUT TYPE="text" NAME="regexp" SIZE=30 VALUE="\b\d\d\d\d\d\b"><P>
<INPUT TYPE="button" VALUE="Is There a Match?" onClick="findIt(this.form)">
<INPUT TYPE="radio" NAME="output">Yes
<INPUT TYPE="radio" NAME="output">No <P>
<INPUT TYPE="button" VALUE="Where is it?" onClick="locateIt(this.form)">
<INPUT TYPE="text" NAME="offset" SIZE=4><P>
<INPUT TYPE="reset">
</FORM>
</BODY>
</HTML>



Regular Expressions: Replacing Strings via Regular Expressions

   
/*
JavaScript Bible, Fourth Edition
by Danny Goodman 
John Wiley & Sons CopyRight 2001
*/

<HTML>
<HEAD>
<TITLE>Got a Match?</TITLE>
<SCRIPT LANGUAGE="JavaScript1.2">
function commafy(form) {
    var re = /(-?\d+)(\d{3})/
    var num = form.entry.value
    while (re.test(num)) {
        num = num.replace(re, "$1,$2")
    }
    form.rumaOutput.value = num
}
function decommafy(form) {
    var re = /,/g
    form.plainOutput.value = form.rumaOutput.value.replace(re,"")
}
</SCRIPT>
</HEAD>
<BODY>
<B>Use a regular expression to add/delete commas from numbers:</B>
<HR>
<FORM>
Enter a large number without any commas:<BR>
<INPUT TYPE="text" NAME="entry" SIZE=15><P>
<INPUT TYPE="button" VALUE="Insert commas" onClick="commafy(this.form)"><P>
The comma version is:<BR>
<INPUT TYPE="text" NAME="commaOutput" SIZE=20><P>
<INPUT TYPE="button" VALUE="Remove commas" onClick="decommafy(this.form)"><P>
The un-comma version is:<BR>
<INPUT TYPE="text" NAME="plainOutput" SIZE=15><P>
<INPUT TYPE="reset">
</FORM>
</BODY>
</HTML>



Regular Expression Switch

   
<html>
<head>
<title>Regular Expression Switch</title>
</head>
<body>
<script type="text/javascript">
var rgExp = /(\w*)-*(\w*)/
var str = "AAAA--BBBB";
var resultStrng = str.replace(rgExp,"$2-$1");
document.writeln(resultStrng);
</script>
</body>
</html>



Regular Expression Tester

   
/*
Mastering JavaScript, Premium Edition
by James Jaworski 
ISBN:078212819X
Publisher Sybex CopyRight 2001
*/
<HTML>
<HEAD>
<TITLE>Regular Expression Tester</TITLE>
<SCRIPT LANGUAGE="JavaScript"><!--
function accessFormElements() {
 flags = ""
 if(document.rexForm.global.checked) flags += "g"
 if(document.rexForm.ignore.checked) flags += "i"
 if(document.rexForm.multiline.checked) flags += "m"
 re = new RegExp(document.rexForm.rex.value,flags)
 rep = document.rexForm.replacement.value
 str = document.rexForm.testString.value
 res = document.rexForm.resultString
}
function searchExp() {
 accessFormElements()
 searchResult = str.search(re)
 if(searchResult==-1)
  res.value = re + " not found."
 else
  res.value = re + " found at position " + searchResult + "."
}
function replaceExp() {
 accessFormElements()
 res.value = str.replace(re,rep)
}
//--></SCRIPT>
</HEAD>
<BODY>
<FORM NAME="rexForm">
<TABLE BORDER="0">
<TR><TD><B>Regular Expression:</B></TD><TD>
<INPUT TYPE="TEXT" SIZE="30" NAME="rex">
<INPUT TYPE="CHECKBOX" NAME="global"><B>Global Match</B>
<INPUT TYPE="CHECKBOX" NAME="ignore"><B>Ignore Case</B>
<INPUT TYPE="CHECKBOX" NAME="multiline"><B>Multiline</B></TD></TR>
<TR><TD><B>Replacement String:</B></TD><TD>
<INPUT TYPE="TEXT" SIZE="30" NAME="replacement">
<INPUT TYPE="BUTTON" VALUE="Search" NAME="search"
 onClick="searchExp()">
<INPUT TYPE="BUTTON" VALUE="Replace" NAME="replace"
 onClick="replaceExp()"></TD></TR>
<TR><TD><B>Test String:</B></TD><TD>
<TEXTAREA ROWS="5" COLS="70" NAME="testString">
This is an example text string for use in search and replace
operations. This string contains a 12345 five-digit number.
This string contains a 123-4567 seven digit number with
an embedded hyphen.
</TEXTAREA></TD></TR>
<TR><TD><B>Result:</B></TD><TD>
<TEXTAREA ROWS="5" COLS="70" NAME="resultString">
</TEXTAREA></TD></TR>
</TABLE>
</FORM>
</BODY>
</HTML>



Searching and Replacing Substrings

   
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/tr/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- 
     Example File From "JavaScript and DHTML Cookbook"
     Published by O"Reilly & Associates
     Copyright 2003 Danny Goodman
-->
<html>
<head>
<title>Recipe 1.7</title>
<link rel="stylesheet" id="mainStyle" href="../css/cookbook.css" type="text/css" />
<script language="JavaScript" type="text/javascript">
function doSR(form) {
  var searchStr = form.srchText.value;
  var re = new RegExp(searchStr, "g");
  var replaceStr = form.replaceText.value;
  var div = document.getElementById("boilerplate");
  div.firstChild.nodeValue = div.firstChild.nodeValue.replace(re, replaceStr);
}
</script>
</head>
<body>
<h1>1.7. Searching and Replacing Substrings</h1>
<hr />
<form action="" onsubmit="return false">
Search for: <input type="text" id="srchText" name="srchText" size="30" value="\(ph\)" /><br />
Replace with: <input type="text" id="replaceText" name="replaceText" size="30" value="PLACEHOLDER REPLACEMENT" /><br />
<div class="buttons"><input type="reset" value="Reset Form" />&nbsp;&nbsp;<input type="button" value="Search and Replace"
onclick="doSR(this.form)" /></div>
</form>
<h2>Boilerplate Text</h2>
<p id="boilerplate">Lorem ipsum dolor sit (ph) amet, consectetaur adipisicing 
elit, sed (ph) do eiusmod (ph) tempor incididunt ut labore et dolore magna 
aliqua. Ut enim adminim veniam, quis (ph) nostrud exercitation ullamco (ph) 
laboris nisi ut aliquip ex ea commodo consequat.</p>
</body>
</html>



Split a string array and get token

   
<html>
<head>
<title>The Split Method</title>
</head>
<body>
<script type="text/javascript">
var inputString = "a=A,b=B,c=C,c="D"";
var arrayTokens = inputString.split(",",3);
for (var i in arrayTokens) {
   document.writeln(arrayTokens[i] + "<br />");
   var newTokens = arrayTokens[i].split("=");
   document.writeln(newTokens[1] + "<br />");
}
</script>
</body>
</html>



Split comma number string

   
<!-- 
     Example File From "JavaScript and DHTML Cookbook"
     Published by O"Reilly & Associates
     Copyright 2003 Danny Goodman
-->
var amounts = "30.25,120.00,45.09,200.10";
var amtArray = amounts.split(/\.\d{2},?/);



String match pattern: (.*)

   
<html>
  <head>
    <script type="text/javascript">
            var pattern = /is (.*) test/;
            var string = "this is a test";
            var result = string.replace(pattern, "not unit $1 test");
            
            document.write(result);
  
    </script>
  </head>
  <body>
  </body>
</html>



String replace with regular expression

   
<html>
  <head>
    <title></title>
    <script type="text/javascript">
        var pattern = /test/;
        var string = "this is a test";
        var result = string.replace(pattern, " unit test");
        
        document.write(result);    
    </script>
  </head>
  <body>
  </body>
</html>



The Backslash in RegExp

   
<html>
<head>
<title>The Backslash in RegExp</title>
</head>
<body>
<script type="text/javascript">
var regExp = /\s\*/g;
var str = "This *is *a *test *string";
var resultString = str.replace(regExp,"-");
document.writeln(resultString);
</script>
</body>
</html>



The Regular Expression Tester

   
/*
JavaScript Unleashed, Third Edition
by Richard Wagner and R. Allen Wyke 
ISBN: 067231763X
Publisher Sams CopyRight 2000
*/

<html>
<head>
<title>Regular Expression Tester</title>
   
<script language="JavaScript">
<!-- begin script
   
// The function searches for the pattern in searchStr
function searchForPattern(searchStr,pattern,REattributes,theResult)
{
  //Create Regular Expression Object
  var regExpObj = new RegExp(pattern,REattributes);
   
  //Populate the result field with the result of the search
  theResult.value = regExpObj.exec(searchStr);
}
   
// This function replaces all occurances of the pattern in
// searchStr with replaceStr
function replacePattern(searchStr,replaceStr,pattern,REattributes,theResult)
{
  //Create Regular Expression Object
  var regExpObj = new RegExp(pattern,REattributes);
   
  //Populate the result field with the result of the search
  theResult.value = searchStr.replace(regExpObj,replaceStr);
}
   
// This function clears all the fields in the page
function clearFields(field1, field2, field3, field4, field5)
{
  field1.value = "";
  field2.value = "";
  field3.value = "";
  field4.value = "";
  field5.value = "";
}
   
// end script -->
</script>
</head>
   
<body>
<center>
<h1>Regular Expression Tester</h1>
<form name="myForm"">
<table board=0>
  <tr align=right>
    <td>Search String:</td>
    <td><input type="text" name="searchString"></td>
  </tr>
  <tr align=right>
    <td>Replace String:</td>
    <td><input type="text" name="replaceString"></td>
  </tr>
  <tr align=right>
    <td>Attributes:</td>
    <td><input type="text" name="REattributes"></td>
  </tr>
  <tr align=right>
    <td>Pattern:</td>
    <td><input type="text" name="pattern"></td>
  </tr>
</table>
<br>
<input type="button"
       value="Search for pattern"
       onClick="searchForPattern(searchString.value,
                                 pattern.value,
                                 REattributes.value,
                                 result)">
<input type="button"
       value="Replace pattern"
       onClick="replacePattern(searchString.value,
                                 replaceString.value,
                                 pattern.value,
                                 REattributes.value,
                                 result)">
<input type="button"
       value="Clear"
       onClick="clearFields(searchString,
                            replaceString,
                            pattern,
                            REattributes,
                            result)">
<br><hr><br>
Result: <input type="text" name="result">
   
</center>
</body>
</html>



Trim a string with regular expression from both sides

   
<HTML>
<HEAD>
<TITLE>Strim a tring</TITLE>
<SCRIPT>
function ltrim(testStr) {
   if (testStr == "")
      return "";
   else {
      var pattern = /[^\s]+.*/;
      result = testStr.match(pattern);
      return result[0];
   }
}
function rtrim(testStr) {
   if (testStr == "")
      return "";
   else {
      var pattern = /.*[\S]/;
      result = testStr.match(pattern);
      return result[0];
   }
}
function trim(testStr) {
   return rtrim(ltrim(testStr));
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="theForm">
<TABLE>
String for trimming:
<INPUT type=text name=testStr size=60>
<INPUT type=button name="theButton" value="Trim" onClick="document.theForm.display.value = trim(document.theForm.testStr.value)";>
<INPUT type=button name="theButton" value="Clear" onClick="document.theForm.testStr.value=""; document.theForm.display.value=""">
Trimmed string:
<INPUT type=text name=display size=60/>
</FORM>  
</BODY>
</HTML>



Try your regular expression here

   
<html>
<head>
<title></title>
<script type="text/javascript">
window.onload=setupEvents;
function setupEvents(evnt) {
   document.someForm.onsubmit=validateField;
}
function validateField(evnt) {
  
  var rgEx = new RegExp(document.someForm.text1.value);
  var OK = rgEx.exec(document.someForm.text2.value);
  if (!OK) {
     alert("Not a match");
  } else {
     alert("The Pattern matched!");
  }
  return false;
}
</script>
</head>
<body>
<form name="someForm">
Regular Expression: <input type="text" name="text1" />
                    <textarea name="text2" cols=50 rows=10></textarea>
                    <input type="submit" value="Check RegExp" />
</form>
</body>
</html>



Use regular expression to validate url

   
<HTML>
<HEAD>
<SCRIPT language="JavaScript">
function check_it()
{
 var theurl=document.f1.t1.value;
 var tomatch= /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/
 if (tomatch.test(theurl)){
     document.write("valid");
     return true;
 }else{
     document.write("invalid");
     return false; 
 }
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="f1" action="#" onSubmit="return check_it();">
URL:<INPUT type="text" name="t1">
    <INPUT type="submit" value="Submit">
</BODY>
</HTML>



Using regular expression (callback function)

   
<html>
  <head>
    <title></title>
    <script type="text/javascript">
        function transformToLowercase(theString)
        {
          return theString.toLowerCase();
        }
        
        var string = "this is a TEST.";
        var pattern = /TEST/;
        var result = string.replace(pattern, transformToLowercase);
        
        document.write( result);
  
    </script>
  </head>
  <body>
  </body>
</html>



Using regular expressions to validate an email

   
<HTML>
<HEAD>
<TITLE></TITLE>
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
function validateEmail(input) {
    var emailPattern = /^\w+@\w+(\.\w{3})$/
    if (emailPattern.test(input)) {
        document.write("valid")
    }
    else {
        document.write("NOT valid")
    }
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
Please enter an e-mail address and click somewhere else on the page:
<INPUT TYPE="text" SIZE="25" onBlur="validateEmail(this.value);">
</FORM>
</BODY>
</HTML>



Validate an email

   
<html>
  <head>
    <title>A valid e-mail address</title>
    <script type="text/javascript">
        var validEmail = "a@t.ru";
        var invalidEmail = "d@t";
        var pattern = /^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+$/;
        
        var a = pattern.test(validEmail);
        var b = pattern.test(invalidEmail);
        
        document.write(validEmail + " is valid: " + a + ", " +invalidEmail + " is valid: " + b);
    </script>
  </head>
  <body>
  </body>
</html>



Whether a string contains only numerical data

   

<html>
  <head>
    <title>Whether a string contains only numerical data</title>
    <script type="text/javascript">
        var numericalString = "3.14159265";
        var characterString = "3 point 1";
        var pattern = /^-?\d+(\.\d+)?$/;
        
        var a = pattern.test(numericalString);
        var b = pattern.test(characterString);
        
        document.write(a + "<BR>" + b);    
    </script>
  </head>
  <body>
  </body>
</html>



Whether a string is a valid phone number

   
<html>
  <head>
    <title>whether a string is a valid phone number</title>
    <script type="text/javascript">
var telephoneString = "(103) 5555 5555";
var emailString = "b@m.ru";
var pattern = /^(\(\d+\) ?)?(\d+[\- ])*\d+$/;
var a = pattern.test(telephoneString);
var b = pattern.test(emailString);
document.write(a + "<BR>" + b);
    </script>
  </head>
  <body>
  </body>
</html>