JSFiddle - React, Tailwind, and code Playground

by greggpollack

HTML

<!DOCTYPE html>
<body>

<h1>Understanding Regular Expressions</h1>
<h2>Level 1 :: Section 3</h2>
<h3>Non-Printables</h3>

<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 3
//Non-Printables

//Problem: Count how many lines exist in a user-submitted poem, so that HTML can be built correctly when the lines are extracted.

//The fiddle will not display changes in whitespace in the following string, but you get the idea. We can show the difference on a slide, obviously.

var poem = "\tIt dropped so low in my regard\r\nI heard it hit the ground\r\nAnd go to pieces on the stones\r\nAt bottom of my mind.\r\n\r\n\tYet blamed the fate that fractured less\r\nThan I reviled myself\r\nFor entertaining plated wares\r\nUpon my silver shelf.\r\n";


//Concept 1 - Nonprintable characters
//These chars have special functionality in RegEx, so to check for them as part of //your actual match, we need to escape them. There are others you can investigate, but these are the most commonly used.
// \t, \r, \n

//Concept 2 - Difference in line termination by OS
//Windows uses \r\n, UNIX \n...so be careful when searching for the ends of lines.

//Let's count lines in a poem, to get an idea of how much vertical space the poem might take up if we formatting it for a webpage.
//Concept 3 - Counting lines in a windows text file
var regEx = /\r\n/g;
document.getElementById("3").innerHTML = "Concept 3: \n" + (poem.match(regEx).length);

//Okay, now let's rewrite the file so that it is Unix-based. This way, all the new lines will be intact when read on a Mac.
//Concept 4 - Replace line transitions to build a Mac file.
var regEx = /\r\n/g;
document.getElementById("4").innerHTML = "Concept 4: \n" + poem.replace(regEx, "\n");

//Let's say the auto-formatting is a little too small for what we'd like, and we'd like to replace all the tabs for each of the poem paragraphs with a larger set of //spaces.
//Concept 5 - Switch all tab formatting to "     "
var regEx = /\t/g;
document.getElementById("5").innerHTML = "Concept 5: \n" + poem.replace(regEx, "      ");

//...and what if we wanted to take out tabs altogether? We'll search for the same tabs,...