Methods of the RegExp Objects

The regex objects provide two methods you can use to find matches: test() and exec(). They both accept a string parameter. test() returns a boolean (true when there's a match, false otherwise), while exec() returns an array of matched strings. Obviously exec() is doing more work, so use test() unless you really need to do something with the matches. People often use regular expressions for validation purposes, in this case test() would probably be enough.

No match, because of the capital J:

/j.*t/.test("Javascript")

false

Case insensitive test gives a positive result:

/j.*t/i.test("Javascript")

true

The same test using exec() returns an array and you can access the first element as shown below:

/j.*t/i.exec("Javascript")[0]

"Javascript"
String Methods that Accept Regular Expressions as Parameters

Previously in this chapter we talked about the String object and how you can use the methods indexOf() and lastIndexOf() to search within text. Using these methods you can only specify literal string patterns to search. A more powerful solution would be to use regular expressions to find text. String objects offer you this ability.

The string objects provide the following methods that accept regular expression objects as parameters:

MethodDescription
match()returns an array of matches
search()returns the position of the first match
replace()allows you to substitute matched text with another string
split()also accepts a regexp when splitting a string into array elements
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +