Use Regex to boost your developer toolbox!

Code on a blue screen with the word 'regex' outstanding.

While we are creating components in our ReactJS/Angular/VueJS projects we end up stumbling upon nice libs. However, sometimes we just need to fix minor things and importing a full lib seems like the only way to do it.

The next command line can be the holy grail – or the most feared one:

$ yarn add cool-text-stuff

Now that we have our data, we need to consult it. Let’s do this?

So, what can we do if we face a problem with the size of our JS bundle and we need to filter inputs or even show the content of a request on screen? Maybe you can consider using the Regex ‘magic’!

Wait, what is Regex?

Yeah, we all know something about Regex when we try to create masks for our inputs or something like this. But what exactly is Regex and how can we really evolve our way of thinking by using it?

Regex is the shorthand for Regular Expressions and it has a lot to do with compilers and programming languages. You can go ahead and search its definition, but if you want a shortcut I can tell you, Regex in JS (or any other language you know) is a nice way to deal and manipulate Strings.

The support for Regex has little differences between languages, but almost all the Regex in this post can be used in any language, even with the (Functional) ones. A simple Regex can be

/[a-z]*@ckl\.io/

That matches any email from Cheesecake in lower-case, without numbers or special characters.

Nice, but how do I use this?

Think that you need to create a mask for an input to match a credit card number. It should match:

  • Only numbers
  • Place a space every 4 digits
  • Do not let the user input more than 16 digits

A nice function to deal with strings and Regex in JS is ‘replace()’. Let’s say that you have a stateless component in ReactJS called ‘Input’. The component’s state is stored by its parent. This means that our component is implemented with an ‘onChange()’ function prop and a value that comes from the parent as a prop as well.

class Parent extends Component {
  // ...
  normalize = value => {
    const newValue = value
      .replace(/\D/g, '')
      .replace(
        /(\d{0,4})(\d{0,4})(\d{0,4})(\d{0,4}).*/g,
        (match, group1, group2, group3, group4) =>
          `${group1}${group2.length > 0 ? ` ${group2}` : ''}${
            group3.length > 0 ? ` ${group3}` : ''
          }${group4.length > 0 ? ` ${group4}` : ''}`
      )
    this.setState({
      value: newValue,
    })
  }

  // ...
  render() {
    const { value } = this.state
      return (
        <Input 
          value={value} 
          onChange={value => this.normalize(value)} 
        />
      )
  }
}

Let’s go over how these Regex were used. In the first Regex we cleaned any value that is not a number and replaced it with empty strings. It is easy to use it because the \D shorthand says “match anything except numbers”.

In the second Regex we want to split the digits into groups of four:

  • \d is the shorthand for [0-9], that means that we can match any number from 0 to 9
  • {0,4} after every \d is telling us that we need to find a match of 0 to 4 digits for each section
  • The parenthesis is where we say: this is a group and as the credit card has 4 groups of 4 digits, we need 4 of them
  • In the end we have the .* saying that we can match anything and we will not treat that
  • The anonymous function is where we receive these groups and treat them: if we have a match, we show the space before each match values except for the first one

With this simple Regex we can save the import of some package that we would possibly increase the bundle size. You can even refactor this function to a service or an utils file to use it inside other components!
You can also search for more Regex used and match any string you want. This works almost like a ‘filter()’ function for arrays: the string is the array and the elements of the array are characters!

Wrapping up

As a  developer I always try to improve my code knowledge and its readability to polish the use of patterns, and to leverage the use of built-in elements of any programming language. As I said earlier, it can save you a few kb of data while dealing with strings, using just one single built-in lib: Regex.

Dealing with complex Regex? Test it online!
If you need to test your Regex, try these websites:

Still having problems? Send me an email and I’ll be glad to help!

About the author.

Ile Caian
Ile Caian

If you are searching for someone to share a great adventure on Middle-Earth (or on Dev-World) and can't find anyone, I'm possibly interested. I also like Music, Books, Linux and learn about new IT topics.