Top Banner
Javascript, The Movie Javascript, The Movie
43

Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Dec 19, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Javascript, The MovieJavascript, The Movie

Page 2: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

TonightTonight

A little more with arraysA little more with arrays Logical Operators and Flow ControlLogical Operators and Flow Control FunctionsFunctions Regular ExpressionsRegular Expressions

Page 3: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Arrays can be indexed or Arrays can be indexed or associative: 20array.htmlassociative: 20array.html

var myfisharray = ["goldfish", "betta", var myfisharray = ["goldfish", "betta", "cichlid", "tuna"];"cichlid", "tuna"];

document.write(myfisharray[0] + "<br />");document.write(myfisharray[0] + "<br />");document.write(myfisharray[3] + "<br />");document.write(myfisharray[3] + "<br />");

var myotherarray = new Array();var myotherarray = new Array();myotherarray["sam"] = "Sam lives here";myotherarray["sam"] = "Sam lives here";myotherarray["susie"] = "Susie lives here";myotherarray["susie"] = "Susie lives here";

document.write(myotherarray["sam"] + "<br />");document.write(myotherarray["sam"] + "<br />");document.write(myotherarray["susie"] + "<br />");document.write(myotherarray["susie"] + "<br />");

There's really no difference, since the number work as labels, but you can use the distinction….

Page 4: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Using Arrays: A Decent Last Using Arrays: A Decent Last ModifiedModified

We looked at the date() method with the We looked at the date() method with the lastModified property of the documentlastModified property of the document

We can use this approach with arrays to We can use this approach with arrays to make a custom last modified time stamp make a custom last modified time stamp for web pagesfor web pages

If you put this in an external script, you If you put this in an external script, you can use the same script to write a can use the same script to write a custom footer for a web site (as I have)custom footer for a web site (as I have)

Page 5: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

An Array of DaysAn Array of Days

Make an array of day names…Make an array of day names…

var days = new Array(8);var days = new Array(8);days[1] = "Sunday";days[1] = "Sunday";days[2] = "Monday";days[2] = "Monday";days[3] = "Tuesday";days[3] = "Tuesday";days[4] = "Wednesday";days[4] = "Wednesday";days[5] = "Thursday";days[5] = "Thursday";days[6] = "Friday";days[6] = "Friday";days[7] = "Saturday";days[7] = "Saturday";

Page 6: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

An object and some variables…An object and some variables…

var dateObj = new Date(document.lastModified);var dateObj = new Date(document.lastModified);var wday = days[dateObj.getDay() + 1];var wday = days[dateObj.getDay() + 1];var lmonth = months[dateObj.getMonth() + 1];var lmonth = months[dateObj.getMonth() + 1];var date = dateObj.getDate();var date = dateObj.getDate();var fyear = dateObj.getFullYear();var fyear = dateObj.getFullYear();

Here, we make a date object and pass Here, we make a date object and pass it's properties into some variablesit's properties into some variables

Page 7: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

<!-- Original source for this script from http://javascript.internet.com/page-details/last-<!-- Original source for this script from http://javascript.internet.com/page-details/last-modified.html#source Modifications (mainly deletions!) by bil haysmodified.html#source Modifications (mainly deletions!) by bil haysvar days = new Array(8);var days = new Array(8);days[1] = "Sunday";days[1] = "Sunday";days[2] = "Monday";days[2] = "Monday";days[3] = "Tuesday";days[3] = "Tuesday";days[4] = "Wednesday";days[4] = "Wednesday";days[5] = "Thursday";days[5] = "Thursday";days[6] = "Friday";days[6] = "Friday";days[7] = "Saturday";days[7] = "Saturday";var months = new Array(13);var months = new Array(13);months[1] = "January";months[1] = "January";months[2] = "February";months[2] = "February";months[3] = "March";months[3] = "March";months[4] = "April";months[4] = "April";months[5] = "May";months[5] = "May";months[6] = "June";months[6] = "June";months[7] = "July";months[7] = "July";months[8] = "August";months[8] = "August";months[9] = "September";months[9] = "September";months[10] = "October";months[10] = "October";months[11] = "November";months[11] = "November";months[12] = "December";months[12] = "December";var dateObj = new Date(document.lastModified);var dateObj = new Date(document.lastModified);var wday = days[dateObj.getDay() + 1];var wday = days[dateObj.getDay() + 1];var lmonth = months[dateObj.getMonth() + 1];var lmonth = months[dateObj.getMonth() + 1];var date = dateObj.getDate();var date = dateObj.getDate();var fyear = dateObj.getFullYear();var fyear = dateObj.getFullYear();document.write('<small>')document.write('<small>')document.write("Last Modified: " + wday + ", " + lmonth + " " + date + ", " + fyear);document.write("Last Modified: " + wday + ", " + lmonth + " " + date + ", " + fyear);document.write('<br />Author: <a href="mailto:[email protected]">bil hays</a> (remove document.write('<br />Author: <a href="mailto:[email protected]">bil hays</a> (remove the SPAM_BLOCK from the address!)');the SPAM_BLOCK from the address!)');document.write('</small>');document.write('</small>');

from general_functions.js

Page 8: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Arrays and External ScriptsArrays and External Scripts

One way to use arrays is to make an external One way to use arrays is to make an external javascript with just the data, and a second external javascript with just the data, and a second external javascript with your program to build the page. javascript with your program to build the page.

This means you can have different data for different This means you can have different data for different pages, each controlled by a single programpages, each controlled by a single program

The basic technique is chunking codeThe basic technique is chunking code One OptionOne Option

Reference the program script as an absolute URLReference the program script as an absolute URL Reference the data array as a relative URLReference the data array as a relative URL

Page 9: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Example:FAQsExample:FAQs

faq_build.js is the script that builds the faq_build.js is the script that builds the page page

faq_data.js holds the datafaq_data.js holds the data faq.html references bothfaq.html references both Starting with this and expanding it would Starting with this and expanding it would

be a fine project if you're getting started be a fine project if you're getting started (what could you add?)(what could you add?)

Page 10: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Logical OperatorsLogical Operators

"and" expressed with &&"and" expressed with && "or" expressed with ||"or" expressed with || "not" expressed with !"not" expressed with ! Thus:Thus:

true && true = true true && false = false true || false = true !true = false

ExampleExample

if (var1 == 1 || var2 == 2)

Page 11: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

= != == != ==== != == != ===

= assigns values= assigns values == denotes equivalence (eg. values are == denotes equivalence (eg. values are

the same)the same) === denotes identity (eg. values AND === denotes identity (eg. values AND

type are the same)type are the same)

Page 12: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

If StatementsIf Statements

Most basic branchMost basic branch Also if/else and if/else if/elseAlso if/else and if/else if/else Can be nestedCan be nested

if (class == "INLS") { if (section == "668") { document.write("hooray!"); } else { document.write("too bad!"); } }

Page 13: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

For loopsFor loops

Loop is run for x times, where x is Loop is run for x times, where x is defineddefined

Brackets for more than one statementBrackets for more than one statement Good for where the variable can be Good for where the variable can be

used for more than just the loopused for more than just the loop

for (count=1;count<=50;count=count + 5) {document.write("The count is " + count + "<br>");document.write("Around the loop again!<br>")}

Page 14: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

While loopsWhile loops

While condition is met, loop continuesWhile condition is met, loop continues Use brackets to enclose multiple Use brackets to enclose multiple

statementsstatements Make sure the condition will be met!Make sure the condition will be met!

count = 1while (count <=15) {document.write("The count is " + count + "<br>");count++;}

Page 15: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Incrementing and DecrementingIncrementing and Decrementing

Use ++ to incrementUse ++ to increment Use -- to decrementUse -- to decrement count++ is the same as count=count+1count++ is the same as count=count+1

Page 16: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Breaking the loopBreaking the loop

Break command: when a condition is Break command: when a condition is met, the loop is broken and control met, the loop is broken and control passes out of the looppasses out of the loop

<SCRIPT LANGUAGE=JavaScript>count = 1;while( count<= 15) { count++ if (count == 10) break; document.write("The count is " + count + "<br>");}</SCRIPT>

Page 17: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Breaking the loopBreaking the loop

Continue command: when a condition is Continue command: when a condition is met, the loop is broken but control met, the loop is broken but control passes to the top of the looppasses to the top of the loop

<SCRIPT LANGUAGE=JavaScript>count = 1;while( count<= 15) { count++ if (count == 10) continue; document.write("The count is " + count + "<br>");}</SCRIPT>

Page 18: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

SwitchSwitchcount = 1;count = 1;while( count<= 15) {while( count<= 15) { switch(count)switch(count) {{ case 5:case 5: document.write("We reached 5!<br>");document.write("We reached 5!<br>"); break; break; case 10:case 10: document.write("Now 10!<br>");document.write("Now 10!<br>"); break;break; case 15:case 15: document.write("Finally, 15, Done!<br>");document.write("Finally, 15, Done!<br>"); break;break; default:default: document.write("The count is " + count + "<br>");document.write("The count is " + count + "<br>"); }} count++; count++; }}

Page 19: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Other control structuresOther control structures

do whiledo while throw, try, catchthrow, try, catch for infor in

Page 20: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

FunctionsFunctions

Good for an action that will be repeatedGood for an action that will be repeated In a way, building a custom methodIn a way, building a custom method Functions can accept parametersFunctions can accept parameters Variable for functions can be local or globalVariable for functions can be local or global

Local variables are known only within the functionLocal variables are known only within the function Local variables are declared with a "var" statementLocal variables are declared with a "var" statement Variables declared otherwise are globalVariables declared otherwise are global

Global variables are available throughout the Global variables are available throughout the documentdocument

Page 21: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Functions: An ExampleFunctions: An Examplefunction dateinbar(){var d = new Date(); var y = d.getFullYear(); var m = d.getMonth() + 1; var d = d.getDate(); var t = m + '/' + d + '/' + y + ' '; defaultStatus = "You arrived at the page on " + t + ".";}

<FORM ACTION="" METHOD=POST name="date_in_bar"> <INPUT TYPE=button NAME="date_in_bar_button" VALUE="Put Date in Status Bar" onclick="dateinbar()"></FORM>

Page 22: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Functions: mouseout_test Functions: mouseout_test

A simple function, called by:A simple function, called by:window.onmouseout = out_text;window.onmouseout = out_text;

function out_text()function out_text(){{if (alert_message[x])if (alert_message[x]) { { window.moveTo(0, 0);window.moveTo(0, 0); window.resizeTo(window.screen.availWidth, window.resizeTo(window.screen.availWidth,

window.screen.availHeight);window.screen.availHeight); alert(x + alert_message[x]);alert(x + alert_message[x]); window.focus();window.focus(); x++;x++; }}}} 25

Page 23: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Silly StuffSilly Stuff

Browsers can detect a lot of eventsBrowsers can detect a lot of events onblur detects when you leave something onblur detects when you leave something

behind, see 26_blur_test.htmlbehind, see 26_blur_test.html You can also manipulate, to an extent, You can also manipulate, to an extent,

windows, although security is closing in windows, although security is closing in there, there, see 27_window_manipulation.htmlsee 27_window_manipulation.html

Page 24: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Functions: SlideshowFunctions: Slideshow

Simple event handler in HTML:Simple event handler in HTML:

<img alt="slide 1" src="data/Slide1.jpg" <img alt="slide 1" src="data/Slide1.jpg" style="width: 720px; height: 540px;" name="main_slide"><br>style="width: 720px; height: 540px;" name="main_slide"><br><img alt="Navigation Previous" src="nav_previous.gif"<img alt="Navigation Previous" src="nav_previous.gif" style="width: 30px; height: 30px;" style="width: 30px; height: 30px;" onclick="change_slide('prev')">onclick="change_slide('prev')"><img alt="Navigation Next" src="nav_next.gif" <img alt="Navigation Next" src="nav_next.gif" style="width: 30px; height: 30px;" style="width: 30px; height: 30px;" onclick="change_slide('next')"><br>onclick="change_slide('next')"><br>

Page 25: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Functions: SlideshowFunctions: Slideshow

Simple function in Javascript, this is a very Simple function in Javascript, this is a very simple manipulation of a DOM object…simple manipulation of a DOM object…

var x = "1";var x = "1";function change_slide(y) {function change_slide(y) { if (y == "next"){if (y == "next"){ x++;x++; }} if (y == "prev"){if (y == "prev"){ x--;x--; }} document.main_slide.src="data/Slide" + x + ".jpg"document.main_slide.src="data/Slide" + x + ".jpg"}} slide_show00.html

Page 26: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

More than one wayMore than one way

You could also build an array….You could also build an array….

var slides = new Array()var slides = new Array()var data_dir = './data';var data_dir = './data';slides[1] = data_dir + '/Slide1.jpg';slides[1] = data_dir + '/Slide1.jpg';// This, for troubleshooting…// This, for troubleshooting…// alert(slides[1]);// alert(slides[1]);slides[2] = data_dir + '/Slide2.jpg';slides[2] = data_dir + '/Slide2.jpg';slides[3] = data_dir + '/Slide3.jpg';slides[3] = data_dir + '/Slide3.jpg';slides[4] = data_dir + '/Slide4.jpg';slides[4] = data_dir + '/Slide4.jpg';slides[5] = data_dir + '/Slide5.jpg';slides[5] = data_dir + '/Slide5.jpg';slides[6] = data_dir + '/Slide6.jpg';slides[6] = data_dir + '/Slide6.jpg';slides[7] = data_dir + '/Slide7.jpg';slides[7] = data_dir + '/Slide7.jpg';slides[8] = data_dir + '/Slide8.jpg';slides[8] = data_dir + '/Slide8.jpg';

Page 27: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

More than one wayMore than one way

……and walk that with eventsand walk that with events

<form action="" method="POST" name="buttons"><form action="" method="POST" name="buttons"><div id="buttons" style="text-align: center;"><div id="buttons" style="text-align: center;"> <input type="button" name="start" value="Start" <input type="button" name="start" value="Start" onclick="slide_number = 1 ; document.slide.src=slides[1];"> onclick="slide_number = 1 ; document.slide.src=slides[1];"> <input type="button" name="previous" value="Previous Slide" <input type="button" name="previous" value="Previous Slide" onclick="slide_number-- ; document.slide.src=slides[slide_number];">onclick="slide_number-- ; document.slide.src=slides[slide_number];"> <input type="button" name="next" value="Next Slide" <input type="button" name="next" value="Next Slide" onclick="slide_number++ ; document.slide.src=slides[slide_number];">onclick="slide_number++ ; document.slide.src=slides[slide_number];"></div></div></form></form>

slide_show01.htmlslide_show01.html

Page 28: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Problems with this slideshow?Problems with this slideshow?

Page 29: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Problems with this slideshow?Problems with this slideshow?

Forward and Back, and Up?Forward and Back, and Up? How many slides?How many slides? Titles?Titles? Skip Slides?Skip Slides? Only one way to navigateOnly one way to navigate

Page 30: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Additions and UpdatesAdditions and Updates

See a var for the total number of slides to control See a var for the total number of slides to control position (this is a hack!), don't fall off the edgeposition (this is a hack!), don't fall off the edge

Multiple functions for actionsMultiple functions for actions And a text box with the path to the slideAnd a text box with the path to the slide

slide_show02.htmlslide_show02.html

function next_slide() function next_slide() {{ if (slide_number < total_slides) if (slide_number < total_slides) {{ slide_number++;slide_number++; document.slide.src= slides[slide_number].src;document.slide.src= slides[slide_number].src; document.text_input_box.text_box1.value = slides[slide_number].src;document.text_input_box.text_box1.value = slides[slide_number].src; }} }}

Page 31: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Things to NoticeThings to Notice

I'm using two arrays, slides and titles in I'm using two arrays, slides and titles in parallel (I could do this with objects)parallel (I could do this with objects)

I've established a convention for namingI've established a convention for naming

Page 32: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

But I also wantedBut I also wanted

Some sort of index of slides with namesSome sort of index of slides with names More flexibility in moving aroundMore flexibility in moving around Aha! Radio buttons, and click on slideAha! Radio buttons, and click on slide So, what I did wasSo, what I did was

Write some pure html form with radio buttonsWrite some pure html form with radio buttons Got that workingGot that working Then put in a titles array and…Then put in a titles array and… Wrote some javascript to output that html with the data Wrote some javascript to output that html with the data

from the titles arrayfrom the titles array Put an event handler on the form to move to any of the Put an event handler on the form to move to any of the

slides, and one on the img, to move forward oneslides, and one on the img, to move forward oneslide_show03.htmlslide_show03.html

Page 33: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Write_titles()Write_titles() function write_titles() {function write_titles() { var open_a = "a";var open_a = "a"; document.write('<form action="" name="title_list" \document.write('<form action="" name="title_list" \ onchange="goto_slide(document.title_list.value)">'); onchange="goto_slide(document.title_list.value)">'); for (slide_number = 1; slide_number<= total_slides; slide_number++) {for (slide_number = 1; slide_number<= total_slides; slide_number++) { if (titles[slide_number] != null) {if (titles[slide_number] != null) { document.write('<input type="radio" name="radio_button" value="' document.write('<input type="radio" name="radio_button" value="' + slide_number + '" onclick="goto_slide(' + slide_number + ')">' + slide_number + '" onclick="goto_slide(' + slide_number + ')">' + titles[slide_number] + '<br>');+ titles[slide_number] + '<br>'); }} else {else { document.write('<input type="radio" name="radio_button" value="' document.write('<input type="radio" name="radio_button" value="' + slide_number+ '" onclick="goto_slide(' + slide_number + ')">' + slide_number+ '" onclick="goto_slide(' + slide_number + ')">' + "Slide Number " + slide_number + '<br>');+ "Slide Number " + slide_number + '<br>'); } } }} document.write('</form>'); document.write('</form>'); }}

Page 34: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Then a cleaner Version…Then a cleaner Version…

slide_show04 is pretty much the sameslide_show04 is pretty much the same but the event handler for the radio buttons but the event handler for the radio buttons

is moved to the button from the formis moved to the button from the form the radio buttons move with slide selectionthe radio buttons move with slide selection

Still requires that you put in the number Still requires that you put in the number of slides, and build an array of titles….of slides, and build an array of titles….

Page 35: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Regular ExpressionsRegular Expressions

Very arcaneVery arcane Very powerfulVery powerful Allows pattern matching for stringsAllows pattern matching for strings Used in string searches, replacements, Used in string searches, replacements,

comparisonscomparisons Javascript regex are like perlJavascript regex are like perl We'll look at some simple examples tonightWe'll look at some simple examples tonight What would you use these for?What would you use these for?

Page 36: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Methods associated with regexMethods associated with regex exec: A RegExp method that executes a search for a match exec: A RegExp method that executes a search for a match

in a string. It returns an array of information. in a string. It returns an array of information. test: A RegExp method that tests for a match in a string. It test: A RegExp method that tests for a match in a string. It

returns true or false. returns true or false. match: A String method that executes a search for a match match: A String method that executes a search for a match

in a string. It returns an array of information or null on a in a string. It returns an array of information or null on a mismatch. mismatch.

search: A String method that tests for a match in a string. It search: A String method that tests for a match in a string. It returns the index of the match, or -1 if the search fails. returns the index of the match, or -1 if the search fails.

replace: A String method that replaces the matched replace: A String method that replaces the matched substring with a replacement substring. substring with a replacement substring.

split: A String method that uses a regular expression or a split: A String method that uses a regular expression or a fixed string to break a string into an array of substrings. fixed string to break a string into an array of substrings.

from http://www.websina.com/bugzero/kb/regexp.html

Page 37: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Building an ExpressionBuilding an Expression

Enclosed in / charactersEnclosed in / characters /abc/ represents the string "abc"/abc/ represents the string "abc" The expression is an object, created one The expression is an object, created one

of two waysof two ways By assignment (note no quotes!)By assignment (note no quotes!)

re = /abc/;re = /abc/; With the RegExp methodWith the RegExp method

re = new RegExp("abc"); re = new RegExp("abc"); Use the latter with user input or where the Use the latter with user input or where the

expression will changeexpression will change

Page 38: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Example of testExample of testfunction testRegEx(string, expression) { re = new RegExp(expression)

if (re.test(string)) { document.write("<p>A match is found!</p>"); } else { document.write("<p>No Match</p>"); } }

RegularExpressions.html

Page 39: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Special CharactersSpecial Characters

^ is used to match the beginning of a string: ^ is used to match the beginning of a string: thus /^The/ matches "The fox"thus /^The/ matches "The fox"

$ matches at the end: thus /fox$/ matches $ matches at the end: thus /fox$/ matches "The fox""The fox"

Square brackets are used to match any one Square brackets are used to match any one of the characters listed: thus [aeiou] matches of the characters listed: thus [aeiou] matches vowelsvowels

\ is used for escaping special characters\ is used for escaping special characters

Page 40: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Special CharactersSpecial Characters

\ is also used for indicating non-\ is also used for indicating non-printable asciiprintable ascii

\n is a new line\n is a new line \r is a carriage return\r is a carriage return \t is a tab\t is a tab \s is a single white space\s is a single white space

Page 41: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Special CharactersSpecial Characters

+ matches the preceding char 1 or more + matches the preceding char 1 or more times, thus /do+m/ matches "dom" and times, thus /do+m/ matches "dom" and "doom""doom"

* matches the preceding char 0 or more * matches the preceding char 0 or more timestimes

. matches any single character. matches any single character ? matches the preceding character 0 or ? matches the preceding character 0 or

1 time1 time

Page 42: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Example in a formExample in a form

Regular_Expression_Form03.htmlRegular_Expression_Form03.html

Page 43: Javascript, The Movie. Tonight A little more with arrays A little more with arrays Logical Operators and Flow Control Logical Operators and Flow Control.

Greedy ExpressionsGreedy Expressions

Expressions are "greedy" by default, Expressions are "greedy" by default, and try to match the maximum number and try to match the maximum number of timesof times