[ITP: Programming A2Z] Regular Expressions

DOM and ES6 Review

  • Arrow functions, “=>”, are a shorthand function notation in ES6

    • Works for anonymous functions which are unnamed

  • Switched from “var” to “let” in ES6 too

  • “this” refers to the current context of where you are in the code

  • Callback functions are synchronous only in JS

  • Promises are not supported in p5.js yet but you can use the fetch() function

    • There are three states: pending, fulfilled, and rejected

    • Fetch() handles asynchronous events using then() and catch() events

  • Made my own word interactor! Could do some interesting things with this in the future…

RegEx Notes

  • RegEx are inside \ ___\

  • meta-characters: “\d” = 0-9, “\w” = A-Z or a-z or 0-9, “\s” = whitespace, “.” = any character

    • Capital letter means opposite or NOT

  • Quantifiers: “*” = 0 or more, “+” = 1 or more, “?” = 0 or 1, “{min, max}” = range, “{n}”

  • Position: “^” = beginning of line, “$” = end of line, “\b” = word boundary

  • Character class [], OR

  • Capturing groups with ()

    • Group 0 is the full regular expression result

    • “$1” and “\1” (back reference) refers to group 1

  • JavaScript functions to use RegEx: test(), match(), exec(), split(), replace()

    • Use flags g = global to return every match to the RegEx or i = case insensitive matches

Assignment - MadLibs Generator

Here is my MadLibs generator and I followed this Coding Challenge.

So as I was following this challenge I saw that the Tabletop.js library is deprecated since 2020 so I transitioned to using something called Papa Parse 5 which converts CSV to JSON.

Here are some other important notes from following the challenge:

  • Need to “escape” the dollar signs in the RegEx because they are meta-characters

  • Whatever you return in the replacer function is what the expression results will be replaced with

  • Global flag!!

  • We kind of touched on this in class but entry.noun = entry[‘noun’]

Now that I’ve completed the MadLib generator, I’ve actually noticed that sometimes a MadLib is generated with all “undefined”’s. My gut instinct is that that would come from the first line of the .csv file but I think that’s accounted for in the Papa Parse declaration with “header: true”. Actually I just realized the “undefined”’s come when I try to generate a MadLib before the file is loaded! Duh!

Another question I have is I guess I am not sure how the "replacer” function really works. Like how does it know the part of speech that corresponds to the matched regular expression?

References

https://thecodingtrain.com/challenges/38-word-interactor

https://www.youtube.com/watch?v=7DG3kCDx53c&list=PLRqwX-V7Uu6YEypLuls7iidwHMdCM6o2w

https://www.papaparse.com/docs