Learn MORE JavaScript on the ServiceNow Platform: Lesson 6 Exercise - Regular Expressions (RegEx)
Okay, So
for your exercise on regular expressions, I'm going to challenge you
to create a regular expression to match a phone number,
specifically in the format of U.S. phone numbers. So open parentheses, three numbers closed parentheses, space three numbers, a dash,
and then four numbers. I want you to come up with a pattern and then test your pattern
against different strings to see if it accurately identify, identifies
phone numbers. I've provided a few hints
to help you with creating that regular expression,
but I'll see you after the pause. Go ahead and pause right now. Okay. Welcome back. Let's see
if you have the same thing that I have. Okay. So I can't just put an open parentheses
because parentheses are reserved characters
within regular expressions, kind of like how you can't
just say d for digit, you have to denote it as a special character. And similarly to a d for digit. I'm going to... I have to escape certain characters
if I want to display it as is. so if I put a backslash
in front of that parentheses, then that basically means
I want it to display as is. and then from the previous lesson, we know that \d means any numerical digit and I want three of them
and then I want to close parentheses, make sure you escape it
with that backslash. The space is a normal space and then again \d for numerical digits. And I want three of them and then a dash
is fine, It doesn't need to be escaped. And then again, four digits. There you go. That's the regular expression
to figure out that specific format. Let's
go ahead and test that inside ServiceNow and run it. Does it match false? What did I do wrong? I see what I did wrong. I put these as parentheses instead of curly brackets. Fun fact, parentheses
groups of parentheses means capture group. And so when I left it like that,
it was actually looking for the specific group of characters
within that parentheses at that moment. So it was looking for another actual
number three, which we don't want it to do that.
We want it to be digits. So I changed it to curly brackets
and then see if it works. There it goes. Now it works. Whoops. That's a good way to see that
you have to go back and check your work.
https://www.youtube.com/watch?v=8fjx7o5ca2s