Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
Learn two common methods in JavaScript that leverage the power of regular expressions: test()
and replace()
.
Resources
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
I want to show you how you can use
regular expressions in JavaScript.
0:00
Let's look at two JavaScript methods we'll
use to accomplish the behavior you saw
0:04
in the demo.
0:09
First, the test method lets you check to
see if a string matches the pattern you've
0:10
defined in a regular expression.
0:14
To use it,
you create a regular expression.
0:17
Then call the test method while
passing the string you wish to check.
0:20
This is the JavaScript equivalent of
typing a regex into the top window of
0:24
regex pal and
a test string into the lower window.
0:29
This method will return true if the regex
matches the string and false if not.
0:33
To format the telephone number,
we'll us replace().
0:38
To use replace(), start with a string,
call replace() on the string,
0:42
passing in a regex to match,
as well as a replacementString.
0:47
Replace() will return a newString
modified to your specifications.
0:52
Let's play with the test and replace
methods in Chrome's DevTools console.
0:57
I'll create a new regular expression,
1:02
this matches corn if it's at
the beginning of a string.
1:05
Now I'll test the string corncob by
calling test on the regular expression.
1:08
Remember test returns a Boolean value,
because corncob begins with corn,
1:16
this evaluates to true.
1:21
Now I'll test popcorn,
this evaluates to false,
1:24
because even though popcorn contains corn,
it is not at the beginning of the string.
1:30
Now let's use this expression
with the replace() method.
1:36
I'll create the string corndog and
store it in a variable string1.
1:40
Now, let's replace corn with hot.
1:49
I'll call replace() on string1, passing
in the regex and the replacement string.
1:52
I get the string hotdog back.
2:00
Now, we'll try replace()
on the string popcorn.
2:03
We'll try to replace it with tart.
2:06
Again, corn isn't matched, because it
isn't at the beginning of the test string.
2:17
No replacement was made and
I got my original string back.
2:22
In the next video, I wanna show you one
more key feature of regular expressions,
2:26
flags, see you there.
2:31
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up