javascript’s regexp. regexp object javascript has an object which compiles regular expressions...
Post on 05-Jan-2016
252 Views
Preview:
TRANSCRIPT
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 is stored in the RegExp object
var g = new RegExp;
RegExp object
uses extended grep as the language (which are typically referred to as Regular Expressions)
Compile the expression order to use it
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!
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
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
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/;
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’)
/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)
Example
var re = new RegExp(”GREP”, “i”);
var str = “stringrep”;
if( re.test(str) )
alert(“found it!”);
Example 2
var re = /grep/i ;
var str = “stringrep”;
if( re.test(str) )
alert(“found it!”);
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
Example
var g = new RegExp(”grep”, “i”);
var str = “stringrep”;
if( str.search(g) )
alert(“found it!”);
Example 2
Preferred modern syntax:
var str = “stringrep”;
if( str.search( /grep/ ) )
alert(“found it!”);
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)
top related