Day 16: Treehouse Full Stack JavaScript Techdegree

Today I learned about JavaScript’s Regular Expressions or “RegEx”. I’ve always wondered how we can validate fields or how we can restrict the contents of what the user inputs using JavaScript. Learning RegEx is definitely a useful skill to have — and i’m sure there are a lot of patterns out there on the web that we can reference to whenever we need to make use of it like a password RegEx or an email RegEx. But learning this is quite helpful since we would know and understand what the Regular Expression actually is and how it works when we apply it to our code. Not to mention the fact that we can construct the regular expression ourselves is a big plus.

These are my notes:

What is a regular expression?

Matching specific characters

Adding a ? before the last letter — makes the last letter optional and if it does show up, it should only repeat itself 1 time

Even for space

Regular expressions by default are case sensitive

We can tell the interpreter to accept either lowercase or uppercase by enclosing the character with square brackets

Character set: enclosing with square brackets — exactly one of the characters in the set should match the character on the string

No matter how many characters we put in the set the set will always match only one position in the string — in this case its the first position

Practice:

Matching Character Ranges

[a-zA-Z] — Basically tells the interpreter that we are allowing all characters either lowercase or uppercase to be allowed

[0–7] even numbers

[0–7a] you can still include characters if you’d like

Practice:

Using wildcard characters

Instead of [0–9] use \d (even though there are two characters, the parser treats this as 1 character)

[0–9] = \d

[A-Za-z_] = \w

[ \t\r\n\f] = \s (whitespace characters), spaces tabs and new lines

. = any character

We can add the wildcard characters in character sets

Practice:

Finding repeated characters

Can match more than one character

* zero or more

+ one or more

Zero or more word characters after y

But if you don’t want to include toy you can use + which means at least 1 or more

Specifying the exact digits or characters

{3} three

{3,} three or more

{3,5} between three and five

\w {5} allows 5 repetitions of \w

AASDF

\d {7} allows 7 repetitions of \d

1234567

Won’t work with 123456 or 12345678

\d{5,} five characters or more — minimum 5

For words AND numbers we can use \w even if its mixed 23DSA23DSA

Practice:

Excluding Characters

[^] negated character set

[^@] match any character set except @ symbol

Note: [.] a dot inside a set is a literal dot and outside . it is a special character that matches anything

\D not a digit

\W not a word

\S not a whitespace

Match

Exclude

Only commas

Only text characters

Alternation

| alternation (or) — tells the parser to either match one pattern or the other

Practice:

Alternation Practice

Groups

Grouping characters allows you to apply modifications to multiple characters the way you have learned to do with single characters

Since . is a wildcard character it would match even $ sign so we should be careful with that

Or we can add \ to it — this is called escaping because we are escaping its normal behavior

Practice:

Beginning and Ending of Strings

These represents location

^ beginning of a string

$ ending of a string

As you can see, it still matches. We have to end the string with $

— — — — — —

What is Validation?

Validation is guarding against receiving bad or inaccurate data

Regular expressions help in validation by matching the input with the pattern that you expect

Validation of user input includes the practice of checking if the input matches the expected type and format

test( ) — to test if the string matches the regular expression

Replace ( ) — replace text in a string by matching a pattern

How to make regular expressions in JavaScript:

Always has to have /____/

Const regexObject = /^word$/ — This is called a literal syntax

  • More concise and easier to read
  • Generally performs better
  • We use this when we know what we want to get from the user

new RegExp(regexpString) — Constructor

test( ) — to test if the string matches the regular expression

regex.test(testString) — returns true / false

Replace ( ) — replace text in a string by matching a pattern

string.replace(regextomatch, whatYouWantToReplaceWithTheMatchedRegex) — returns a new string modified to your specifications

Flags: lets you change what a regular expression matches in some way.

  • Overrides a default behavior of regular expressions

i — case insensitive

g — global (by default the regular expression stops searching once it finds a match- the g flag tells the parser to find all matches contained in a string)

m — multiline (will treat line breaks like new lines ^will mark the beginning of a new line and a $will match the end)

To add a flag to a regex in JavaScript put them after the last / of a regex literal

/regex/igm

Without case sensitive

Validating a username

But if you add lowercase in the start or end

It won’t work. Because the parser is looking for lowercase characters and the string in the input contains lowercase even if there is an uppercase. So what we have to do is add ^ to the beginning to say that at the beginning, we will only accept lowercase and add $ to the end saying that we are only accepting lowercase until the end.

Validating Password

Must contain:

Uppercase

Lowercase

Number

We can use the && operator to make sure each returns true, if one returns false then the whole statement is false. Which will then show the error message.

Validating the Phone Number

Must have the format of (555) 555–5555

This only returns true or false, basically you are making the user input the format of what the telephone should be. But there is also a way for them not to do that and for us to automatically format it ourselves once the user enters the input value for telephone number.

Valid Email

What can be added to a string to eliminate partial matches? ^ at the beginning and $ at the end.

— — —

Using replace with captured groups — captured groups make regular expressions even more powerful by allowing you to pull out patterns from within the matched pattern. Then you can rearrange the matched string as needed.

Use () to group and capture sets of characters

$1 represents the first group

$2 represents the second group

$3 represents the third group

The $ is basically storing the values it is receiving from the string and returning it in the way we ordered it

I need to be able to accept both

\D means any non digit which includes spaces and dashes. Just in case users put extra spaces we can do this: * because it means 0 or more. Having this makes it much more flexible

Reformatting the telephone number when the user presses enter or tabs it will our form will automatically format the telephone number

Index numbers for captured expressions begin to be numbered at 1

What can you put in a replacing string to recall a captured value? A $ followed by an integer

replace ( ) methods are called on a string

What can regular expressions match? Patterns in strings, precise strings, numerals in strings, repeated strings