JSFiddle - React, Tailwind, and code Playground
by greggpollack
HTML
<!DOCTYPE html>
<body>
<h1>Understanding Regular Expressions</h1>
<h2>Level 1 :: Section 2</h2>
<p id="1"></p>
<p id="2"></p>
<p id="3"></p>
<p id="4"></p>
<p id="5"></p>
<p id="6"></p>
<p id="7"></p>
<p id="8"></p>
<p id="9"></p>
<p id="10"></p>
<p id="11"></p>
<p id="12"></p>
</body>
JavaScript
//Level 1
//Section 2
//Escaping Reserved Characters
//Problem: Count how many different bracketed item IDs are present in a text //inventory file (here expressed with string), so that we can know how many //different customized price tags we'll need to create in our brick-and-mortar book //store.
var inventory = "Great Expectations\t\tCharles Dickens\t\t{D29}\n"+
"The Joy Luck Club\t\tAmy Tan\t\t{T40}\n" +
"The Joy Luck Club\t\tAmy Tan\t\t{T40}\n" +
"Starship Troopers\t\tRobert Heinlein\t\t{H12}\n" +
"Crime and Punishment\t\tFyodor Dostoyevsky\t\t{D43}";
//...etc.
//Concept 1 - Reserved Characters
//These chars have special functionality in RegEx, so to check for them as part of your actual match, we need to escape them.
// \, ^, $, ., |, ?, *, +, (, ), [ ], {, }
//Concept 2 - Escaping with Backslash
//To search for the { in our actual text...
var regEx = /\{/g;
document.getElementById("2").innerHTML = "Concept 2: \n" + inventory.match(regEx);
//Concept 3 - Retrieving a count from the amount of matches.
//Then, to get the number we need...
var regEx = /\{/g;
document.getElementById("3").innerHTML = "Concept 3: \n" + inventory.match(regEx).length;
//Concept 4 - Can combine escaped characters with literals.
//We'll count how many Item ID's begin with the letter D, to see how many titles we have in stock by authors with last names beginning with D.
var regEx = /\{D/g;
document.getElementById("4").innerHTML = "Concept 4: \n" + inventory.match(regEx).length;
//Concept 5 - Multiple escapes are cool, too.
//A distributor wants to check on a title availability by ID Number.
var regEx = /\{B33\}/;
document.getElementById("5").innerHTML = "Concept 5: \n" + inventory.match(regEx);
//...oops, no inventory for that ID. How bout another?
//Concept 6 -
var regEx = /\{T40\}/;
document.getElementById("6").innerHTML = "Concept 6: \n" + inventory.match(regEx);
//We do have it in stock!
//And he wants...