Download presentation
Presentation is loading. Please wait.
Published byClaire Phelps Modified over 9 years ago
1
Regular Expressions CSE 33451
2
Regex Links MDN Regular Expressions Regexpal
3
Regular Expressions Patterns used to match character combinations in strings. In JS, regular expressions can be used with the RegExp object and with the String object. CSE 33453
4
Regex Use Cases Find and extract data from a document. Validate content supplied in a form before it is submitted. – Telephone numbers – SSN – Email addresses – Anything that follows a pattern CSE 33454
5
Regex Syntax Regular expressions are an extremely powerful tool implemented in most languages; however… Regular expressions have their own syntax and usage of special characters. Difficult to remember if you use them infrequently. CSE 33455
6
Regex Special Characters: ^ CSE 33456 Regex: ^A Matches: “Aaaann Animal Named Alex” Doesn’t match: “an A” CharacterMeaning ^Matches the beginning of input
7
Regex Special Characters: $ CSE 33457 Regex: t$ Matches: “Today I ate a tart” Doesn’t match: “tart is here” CharacterMeaning $Matches the end of input
8
Regex Special Characters: * CSE 33458 Regex: a* Matches: “aaaaaaaaaaaaaallred” Matches: “tart” Doesn’t match: “tom” //Star and Question Mark Characters are useful for the patterns with some variation. Regex: a*m Matches: “tom” *Novice users often overuse/misuse this character.* CharacterMeaning *Matches the preceding character 0 or more times.
9
Regex Special Characters: + CSE 33459 Regex: 1+ Matches: “911” Matches: “912” Doesn’t match: “8675309” CharacterMeaning +Matches the preceding character 1 or more times.
10
Regex Special Characters: ? CSE 334510 Regex: l? Matches: “lily” Matches: “llog” Doesn’t match: “Ron” CharacterMeaning ?Matches the preceding character 0 or 1 more times.
11
Regex Special Characters:. CSE 334511 Regex:.n Matches: “nay, an apple is on the tree” Doesn’t match: “nay, an apple is on the tree” CharacterMeaning.(The decimal point) matches any single character except the newline character.
12
Regex Special Characters: | CSE 334512 Regex: red|blue Matches: “hand me that blue crayon” Matches: “hand me that red crayon” Doesn’t match: “hand me that black crayon” CharacterMeaning |Matches one pattern or the other
13
Regex Syntax: {n} Regex: a{2} Matches: “Caandy” Matches: “Caaandy” Doesn’t match: “Candy” CSE 334513 SyntaxMeaning {n}Where n is a positive number. Matches exactly n occurrences.
14
Regex Syntax: {n,m} Regex: a{1,3} Matches: “Candy” Matches: “Caaandy” Matches: “Caaaandy” Doesn’t match: “Cndy” CSE 334514 SyntaxMeaning {n,m}Where n and m are positive integers. Matches at least n and at most m occurrences of the preceding character. When either n or m is zero, it can be omitted.
15
Regex Syntax: [xyz] Regex: [a-d] Matches: “candy” Matches: “brisket” CSE 334515 SyntaxMeaning [xyz]Character set. Matches any one of the enclosed characters.
16
Regex Syntax: [xyz] Regex: [0-5] Matches: “0123456789” Matches: “543210” CSE 334516 SyntaxMeaning [xyz]Character set. Matches any one of the enclosed characters.
17
Regex and Javascript MethodDescription testA RegExp method that tests for a match in a string. It returns true or false. matchA String method that executes a search for a match in a string. It returns an array of information or null on a mismatch. searchA String method that tests for a match in a string. It returns the index of the match, or -1 if the search fails. replaceA String method that executes a search for a match in a string, and replaces the matched substring with a replacement substring. splitA String method that uses a regular expression or a fixed string to break a string into an array of substrings. CSE 334517
18
Sample Regex To use a regex in javascript, surround the regex with forward slashes For example, I have the regex [a-z]. To use it in javascript I would do the following. var regex = /[a-z]/; //matches any lower case character that is in the alphabet a-z. var string = "tom"; string.match(regex); // ["t"] CSE 334518
19
Advanced Regex Flags Regular expression have four optional flags that allow for global and case insensitive searching. These flags can be used separately or together in any order, and are included as part of the regex. CSE 334519
20
Advanced Regex Flags Example "tom".match(/T/); // null //Using the i flag you can perform case insensitive searches. "tom".match(/T/i); // ["t"/ CSE 334520
21
Regex Challenge Write a regular expression that will only accept a string that contains lower and upper case alphabet characters Underscore characters Must have an inclusive length between 8 and 32. CSE 334521
22
XMLHttpRequest Reference Links MDN Jibbering.com OpenJS XMLHttpRequest Example CSE 334522
23
AJAX Quickfacts Using the XMLHttpRequest API is what is known as AJAX. Asynchronous Javascript and XML. Used to send data back and forth from client to server without leaving a webpage. CSE 334523
24
AJAX Quick facts AJAX is the combination of HTML, CSS, and Javascript. Makes sending HTTP request fast and easy. Wasn’t very popular until Microsoft’s Outlook Web Access (2000) and Google’s Google Maps(2005) and Gmail(2004). CSE 334524
25
How AJAX Works CSE 334525
26
Creating an XMLHttpRequest() Older browsers, IE5 and IE6, use a different method. Newer browsers do the following: var request = new XMLHttpRequest(); CSE 334526
27
Initialize a request Use the open() method to initialize a request. //open() interface void open(DOMString method, DOMString url, optional boolean async, optional DOMString user, optional DOMString password ); CSE 334527
28
open() : Required Parameters 1.method - The HTTP method to use, such as "GET", "POST", "PUT", "DELETE", etc. 2.url - The URL to which to send the request. CSE 334528
29
open() : Optional Parameters 3.async - An optional boolean parameter, defaulting to true, indicating whether or not to perform the operation asynchronously. If this value is false, the send()method does not return until the response is received. 4.user - The optional user name to use for authentication purposes; by default, this is an empty string. 5.password - The optional password to use for authentication purposes; by default, this is an empty string. CSE 334529
30
open() example var request = new XMLHttpRequest(); request.open("GET", "www.google.com", false); CSE 334530
31
Send the request var request = new XMLHttpRequest(); request.open("GET", "www.google.com", false); request.send(); CSE 334531
32
Handling a response message When the server receives the client request, it will perform any necessary actions and return back to the client a response message. In most cases, the only handling required is to check the response status code, and if everything is okay access the responseText. CSE 334532
33
Handling a response message var request = new XMLHttpRequest(); request.open("GET", "www.google.com", false); request.send(); if (request.status === 200) { //200 is an HTTP status code. console.log(request.responseText); //print resp txt to console } CSE 334533
34
Response Messages attributes/methods 1.status – returns HTTP Status code 2.statusText – returns HTTP status text 3.getResponseHeader() – get specified header from response message. 4.getAllResponseHeaders() – get all headers from response message. CSE 334534
35
Handling a response message 5.responseType – returns the format the response is in: "arraybuffer", "blob", "document", "json", and "text“. 6.response – returns of the response entity body. 7.responseText – returns the text of the response entity body. 8.responseXML – returns a DOM object of an xml document. CSE 334535
36
Your Turn Using this fiddle as basis, make an XMLHttpRequest to http://lyle.smu.edu/~craley/3345/http/showResponse.php.fiddle http://lyle.smu.edu/~craley/3345/http/showResponse.php CSE 334536
37
Using Query Parameters If you recall, GET and POST requests can send a key-value name pair along with an HTTP request. This is useful for adding query parameters to your request. CSE 334537
38
Query Parameters Example A typical example would look like this: name=Tim&lastname=Drake&age=17&alias=Robin CSE 334538
39
GET Request When sending a GET request, you combine the url with query parameters separated by a question mark. http://www.google.com?name=Tim&lastname=Drake&age=17&alias=Robin CSE 334539
40
GET Request with Query Parms in JS var url = 'http://www.google.com'; var parms = 'name=Tim&lastname=Drake&age=17&alias=Robin'; request.open('GET', url+"?"+parms, false); request.send(); CSE 334540
41
POST Request When sending a POST request, the HTTP Message includes the query parameters as apart of the message body. Additional information about the query parameters are sent as header info: – Content type – Content length – Etc CSE 334541
42
POST Request with Query Parms in JS var url = 'http://www.google.com'; var parms = 'name=Tim&lastname=Drake&age=17&alias=Robin'; request.open('POST', url, false); //Send the proper header information along with the request. //Depending on the data type (xml, json, etc) you would modify the content type header. request.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); request.send(parms); See jsFiddlejsFiddle CSE 334542
43
Full XMLHttpRequest Example http://lyle.smu.edu/~craley/3345/http/httpRe quest.html http://lyle.smu.edu/~craley/3345/http/httpRe quest.html CSE 334543
44
Synchronous Requests So far we’ve only seen synchronous requests. These requests pause code execution and wait until a response is given from the server before continuing. Depending on the request you could be paused for a long time. Not ideal for practical purposes. CSE 334544
45
Asynchronous Requests These requests provide a callback function that is triggered when the server responds. Code execution isn’t paused. This is what you should be using in your code. CSE 334545
46
Async XMLHttpRequest Example var url = "http://www.google.com"; var request = new XMLHttpRequest(); request.onreadystatechange = function() { //readyState === 0 : UNSENT. Means open() hasn't been called //readyState === 1 : OPENED. Means send() hasn't been called //readyState === 2 : HEADERS_RECEIVED. Means send() has been called //and headers have been received //readyState === 3 : LOADING. Means downloading //readyState === 4 : DONE. The operation is complete if (request.readyState === 4) { document.body.innerHTML = request.responseText; } request.open('GET', url, true); request.send(); See jsFiddlejsFiddle CSE 334546
47
XMLHttpRequest Bummer Unless you have been given permission, you cannot successfully make an HTTP Request to another server. – Cross Domain Request Work arounds for this are – Use a different scripting language (PHP, Python) – Use JSONP – If you have access to the different sever, you can get Cross Domain Request permission. CSE 334547
48
JSON Reference Links JSONLint – a JSON validator JSONLint MDN JSON.org CSE 334548
49
JSON Quick facts JSON – javascript object notation JSON is a collection of name value pairs Is a data-exchange format. Closely resembles Javascript syntax. Can parse JSON into a JS object. CSE 334549
50
Hello World JSON Example { “fname" : “bruce" } CSE 334550 1.All JSON data starts and ends with a curly brace or square brace 2.The curly brace is what encapsulates the data into an Object. 3.After all, JSON stands for Javascript Object Notation. Object
51
Hello World JSON Example { “fname" : “bruce" } CSE 334551 namevalue pair
52
Hello World JSON Example { “fname" : “bruce" } CSE 334552 namevalue pair The name portion of the pair must ALWAYS be a String.
53
Hello World JSON Example { “fname" : “bruce" } CSE 334553 valuename pair The value portion of the pair can be several different types.
54
Value types 1.numbers 2.booleans 3.Strings 4.null 5.arrays (ordered sequences of values) 6.objects (string-value mappings) composed of these values (or of other arrays and objects). CSE 334554
55
JSON Example { "age": 21, "name": "Sandra Dee", "alive": false } It is necessary to separate each pair with a comma. Your JSON will be invalid if you don’t. CSE 334555
56
JSON Array Example { "scores": [ 100, 89, 99, 75] } An array is an ordered collection of values. An array begins with a [ (left bracket) and ends with ] (right bracket). Values are separated by a, (comma). CSE 334556
57
Object in JSON Just like typical Object-Oriented Programming, you can have objects inside of objects { “pizza” : { “name” : “The Heart Attack”, “id” : 20121, “toppings” : [ “Pepperoni”, “Cheese”, “Chili” ], “price” : 19.99 } CSE 334557
58
JSON Example { "type": "document", "students": [ "tom", "sally", "joe" ], "class room": 112, "teach": "Hank McCoy“, “fulltime” : false } CSE 334558
59
Dissect the JSON Data { "type": "document", "students": [ { "name": "tom", "age": 18 }, { "name": "sally", "age": 18 }, { "name": "joe", "age": 17 } ], "class room": 112, "teacher": "Hank McCoy", "fulltime": false } CSE 334559
60
Create a JSON Object var class = { "type": "document", "students": [ "tom", "sally", "joe" ], "class room": 112, "teach": "Hank McCoy" }; CSE 334560
61
Navigating a JSON Object var json = { "type": "document", "students": [ { "name": "tom", "age": 18 }, { "name": "sally", "age": 18 }, { "name": "joe", "age": 17 } ], "class room": 112, "teacher": "Hank McCoy", "fulltime": false } CSE 334561 JSON Objects are just Javascript Objects, therefore, its easy to access pairs inside the object. To access a pair, use the pair’s name as an attribute of the object to access the value.
62
Navigating a JSON Object var json = { "type": "document", "students": [ { "name": "tom", "age": 18 }, { "name": "sally", "age": 18 }, { "name": "joe", "age": 17 } ], "class room": 112, "teacher": "Hank McCoy", "fulltime": false } CSE 334562 json.type; // “document” json.students[0].name; // “tom” json.students[0].age; // 18 json.students[1].name; // “sally” json.students.length; // 3 json[“class room”]; // 112 json.teacher; // “Hank McCoy” json.fulltime; // false
63
JSON Methods JSON.stringify() to convert object to JSON string JSON.parse() to convert JSON string to JS Object. CSE 334563
64
JS Object JSON JS Object //Create a javascript Object var foo = {}; foo.bar = "something"; foo.baz = 7; //Converts JS Object into a JSON string var json = JSON.stringify(foo); //"{"bar":"something","baz": 7}“ //Converts JSON string back into JS Object json = JSON.parse(json); console.log(json.bar); // “something” console.log(json.baz); // 7 CSE 334564
65
Your turn Use AJAX to fetch the following JSON: http://lyle.smu.edu/~craley/3345/http/drink_genie/supplies.json http://lyle.smu.edu/~craley/3345/http/drink_genie/supplies.json Print out to the console the JSON data for all pairs whose name equals quantity. CSE 334565
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.