Presentation is loading. Please wait.

Presentation is loading. Please wait.

Javascript’s RegExp. RegExp object Javascript has an Object which compiles Regular Expressions into a Finite State Machine The F.S.M. is internal, and.

Similar presentations


Presentation on theme: "Javascript’s RegExp. RegExp object Javascript has an Object which compiles Regular Expressions into a Finite State Machine The F.S.M. is internal, and."— Presentation transcript:

1 Javascript’s RegExp

2 RegExp object Javascript has an Object which compiles Regular Expressions into a Finite State Machine The F.S.M. is internal, and is stored in the RegExp object var g = new RegExp;

3 RegExp object uses extended grep as the language (which are typically referred to as Regular Expressions) Compile the expression order to use it

4 RegExp object new RegExp(”grep_string”, “options”); Using it is FAST, which is why grep patterns are so popular Creating/compiling the RegExp object is SLOW!

5 RegExp Options Optional parameter (flags):...new RegExp(”string”, “ig”) regExpObj.compile(”string”, “gi”); i= ignore case g= global (find every match) allows replace all + useful in loops

6 RegExp object re= new RegExp( /querystring/ ); re.test( “someText” ); re.exec( “someText” ); returns an array of results [0] is found string [>=1] is found parts() in that string

7 Alternate Methods Some browsers promote 1 method over another var x = new RegExp(”string”); vs (preferred) var x = new RegExp(/string/); vs (not recommended but shortest) var x= /string/;

8 RegExp Options multiline problem m=multiline flag is NOT supported multiline is a global boolean property of RegExp object itself if not supported; you can test for it. if( typeof(RegExp.multiline) == ‘Boolean’)

9 /Common Use/ /string/ similar to “quotes” on strings if you use “string” you must escape: /\d\d/ (match 2 digit pattern) vs “\\d\\d” (match 2 digit string)

10 Example var re = new RegExp(”GREP”, “i”); var str = “stringrep”; if( re.test(str) ) alert(“found it!”);

11 Example 2 var re = /grep/i ; var str = “stringrep”; if( re.test(str) ) alert(“found it!”);

12 String Object.search(regexp) returns position found or -1.replace(regexp, string) returns new string or old string.match(regexp) returns array of matches or null

13 Example var g = new RegExp(”grep”, “i”); var str = “stringrep”; if( str.search(g) ) alert(“found it!”);

14 Example 2 Preferred modern syntax: var str = “stringrep”; if( str.search( /grep/ ) ) alert(“found it!”);

15 Learning Use a Text Editor that supports RegExp or Grep Patterns (even better if it claims Perl Reg. Exp.) Use the Regular Expression Play Pen webpage (class website) Use javascript (code, make your own test page, or javascript console)


Download ppt "Javascript’s RegExp. RegExp object Javascript has an Object which compiles Regular Expressions into a Finite State Machine The F.S.M. is internal, and."

Similar presentations


Ads by Google