In hindsight, I now realize that it wasnt actually that scary after all.

In face, it was an easy way to solve the problem in hand.

But why did I ever feel this way?

Javascript regular expressions aren’t that daunting — here’s how to design your own

My intention here is not to scare you because regex can be simple.

So, first.

What are regular expressions?

Article image

Regular expressions are a way to describe patterns in data strings.

But what kind of patterns are we talking about?

once you nail the pattern, what can you do with the regular expressions?

Article image

With that said, in other languages there may be some differences in the way they treat regular expressions.

Lets look at an example that will validate if the string contains the wordHelloor not.

However, the first example has a more familiar look, instancing an object with astringas a parameter.

Article image

So sorry about that, but thats just how it is.

Before you use it somewhere else you will have to test it and adjust it if necessary.

Returns a result array, or null.

Article image

It returns the index at which the matched happened, or -1 is there is no match.

If the pattern is a string, only the first occurrence will be replaced.

Note that the original string will remain unchanged.

Article image

Hence the reason why on the second console.log the word dog got replaced only once.

But we will cover more on that later.

Anchoring

This will matchhellowherever it was put inside the string.

Article image

But, what do I mean by range?

But once you get the hang of them, theyre pretty cool.

This article was originally published onLive Code StreambyJuan Cruz Martinez, founder and publisher of Live Code Stream.

Article image

Sign up for updates on everything related to programming, AI, and computer science in general.

Also tagged with

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image