DEV Community

codeToBug
codeToBug

Posted on • Originally published at codetobug.dev

Unleashing the Sorcery of JavaScript Regular Expressions: Now You See Me, Now You Don't!

Dive into the cryptic world of JavaScript Regular Expressions. Picture yourself as a wizard, casting spells over text strings. Prepare to warp reality—or just data, whatever floats your broomstick.

So you want to master the mystic arts of JavaScript Regular Expressions, huh? Well, brave sorcerer, strap on your pointy hat, grab your wand, and let's weave magic over unsuspecting strings of text, shall we?

Let's start with the first spell—sorry, I mean "Regular Expression"—in our grimoire. Want to find a sneaky word hiding within a text, playing a medieval version of Hide 'n Seek? Here's a little incantation that works like a divination charm:

let text = "Once upon a midnight dreary, while I pondered, weak and weary";
let mySpell = /dreary/;
console.log(mySpell.test(text)); // It's like shouting "Reveal yourself, dreary!"
Enter fullscreen mode Exit fullscreen mode

What do you think it returns? A ghost? No, my dear Merlin, it’s not that complex. It just gives a simple "true" or "false". Boolean values. Not very Hogwarts-y, but that's the mundane life of a JavaScript mage for you.

Next, let's say you're trying to attract all the numbers in a text. Like a magnet spell for numerals. Yes, you can totally do that. Here's how you enchant a string to reveal all its hidden digits:

let text = "I have 7 horcruxes, 3 broomsticks, and 1 very fancy hat.";
let numberSpell = /\d+/g;
console.log(text.match(numberSpell)); // Shout, "Numbers, assemble!"
Enter fullscreen mode Exit fullscreen mode

And, voila! You'll see ["7", "3", "1"]—the numbers, plucked from their cozy textual abode. Magic? More like Regular Expressions. But hey, six of one, half a dozen of the other.

Meta characters

Ah, back to the magical world of Regular Expressions we go! Let's decode the secret ingredients—the meta-characters—that infuse our spells with their unique powers. Remember, a master wizard is not made in a day, so take your time understanding these formula elements.

1. Dot .

The dot is like the all-purpose eye of a newt. It morphs into any character you need, except a fresh line break. But remember, it can transform just once:

let allSeeingDot = /b.t/g; // A "bat", "bit", or "but", it matters not!
Enter fullscreen mode Exit fullscreen mode

2. Caret ^

The caret is the rooster's crow, signaling the break of dawn. It signifies the start of a line:

let roostersCrow = /^Alohomora/g; // Only works if "Alohomora" is the first spell of the day!
Enter fullscreen mode Exit fullscreen mode

3. Dollar Sign $

Much like the sandman's dust, the dollar sign signifies the end. It's concerned only with the end of a line:

let sandmansDust = /nocturne$/g; // Only "nocturne" at the end of a lullaby will do.
Enter fullscreen mode Exit fullscreen mode

4. Star * and Plus +

The star is like your infinite bag of fairy dust, allowing for zero or more characters. The plus is its more demanding sibling; it insists on at least one character:

let fairyDust = /ho*/g; // Can summon "h", "ho", "hoo", "hooo"... an endless bag indeed.
let demandingDust = /ho+/g; // But this one needs at least one "o" after "h". More is merrier though!
Enter fullscreen mode Exit fullscreen mode

5. Question Mark ?

The question mark is akin to the elusive unicorn. It allows for the mythical 'maybe'— zero or one occurrence of the character before it:

let elusiveUnicorn = /wiz?ard/g; // Transforms into both "wizard" and "ward". It's a unicorn, after all!
Enter fullscreen mode Exit fullscreen mode

6. Backslash \

The backslash is the powerful ward of protection. It safeguards special characters, allowing them to be used in their true form:

let protectiveWard = /\$5/g; // No transformation this time, just a good old dollar sign.
Enter fullscreen mode Exit fullscreen mode

7. Square Brackets []

The square brackets are like your friendly house elves, working only for specific characters:

let faithfulElves = /[abc]/g; // Only "a", "b", and "c" shall pass.
Enter fullscreen mode Exit fullscreen mode

8. Parentheses ()

Parentheses are akin to your time turner, capturing a moment (group of characters) to be revisited later:

let timeTurner = /(expelli)armus/g; // Captures "expelliarmus", but "expelli" is stashed away in the time capsule.
Enter fullscreen mode Exit fullscreen mode

9. Pipe |

The pipe is your potion of choice, denoting 'or'. It chooses the pattern before or after it:

let potionOfChoice = /gryffindor|hufflepuff/g; // Whether you're a lion or a badger, this potion has got your back.
Enter fullscreen mode Exit fullscreen mode

So, there you go! Your magical guide to the meta-characters that power the world of Regular Expressions in JavaScript. Use these formula elements wisely, keep weaving your spells, and you'll be conjuring powerful Regular Expressions in no time!

Ah, wizard of Regex, eager to learn more spells to bend the universe of text to your will, are we? Good! Now, gather round as we conjure further mysteries of Regular Expressions in JavaScript.

1. Matching an Email Address

Need to pluck out an email address from the chaotic cacophony of characters? Try this magical formula:

let text = "You can reach me at gandalf@middleearth.com";
let emailSpell = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/;
console.log(text.match(emailSpell)); // Shout, "Email, reveal thyself!"
Enter fullscreen mode Exit fullscreen mode

And there you have it, "gandalf@middleearth.com" will pop up faster than you can say "You shall not pass"!

2. Capturing Text Between Double Quotes

Hidden messages between double quotes, you say? Unravel them with this simple incantation:

let text = '"Speak "friend" and enter." "Mellon"';
let quoteSpell = /"(.*?)"/g;
console.log(text.match(quoteSpell)); // "Secrets in quotes, come forth!"
Enter fullscreen mode Exit fullscreen mode

Here come "friend" and "Mellon", stepping out from the shadows between the quotes!

3. Get Content Inside an HTML Tag

Looking to sneak a peek inside an HTML tag? Here's a spell that does the trick:

let text = "<title>One Ring to Rule Them All</title>";
let htmlSpell = /<title>(.*?)<\/title>/;
console.log(text.match(htmlSpell)[1]); // Shout, "Title, unveil thy contents!"
Enter fullscreen mode Exit fullscreen mode

And just like that, "One Ring to Rule Them All" is revealed, just as it was hidden within the 'title' tags.

And remember, dear wizard, with great Regular Expression power comes great text-manipulating responsibility. Use your newfound powers wisely!

So there you have it, aspiring Regular Expressions sorcerers. We've scratched the surface of our mystical, text-manipulating adventure. It's a ride that's as unpredictable as a potion mixing class, and just as fun. One thing's for sure, though, the more you dive into JavaScript Regular Expressions, the less 'regular' they seem. So, keep practicing your spells, keep honing your craft, and soon enough, you'll be the Dumbledore of JavaScript Regular Expressions!

Top comments (0)