Beginning to Use Regex in Javascript

Cristina Murillo
4 min readFeb 24, 2019

--

You will wish you learned it sooner.

It’s incredibly useful, and if you already know Javascript this tool is well within your reach. It may look like nonsensical hieroglyphs, but once you pick up a few tricks it’s actually more readable than the alternative longhand Javascript. So what is a regular expression?

“A sequence of characters that define a search pattern.” -Wikipedia

Why should you learn it?

  • Much simpler to complete find, and find and replace operations
  • Input validation

Finding Vowels Example

Consider this classic vowels problem: Write a function that returns the number of vowels used in a string. Vowels are the characters ‘a’, ‘e’,‘i’, ‘o’, and ‘u’. For example, ‘Hi There!’ should return `3`.

With vanilla Javascript, you might produce something like the following:

Solution to the vowels problem without regex

In the above you create an array of vowels, and a variable to keep track of the vowel count. You then iterate over a lower case version of the string you are checking, and up the vowel count each time a character is a vowel. With regex, the above would be simplified to this:

Solution to the vowels problem with regex

Reading through the above is not as extraterrestrial as you may first think. If a string has a match for ‘aeiou’, then return the number of matches it has (more on the match() method in a moment), else return 0.

Breaking it down

Let’s start with building up the regex. The literal notation for regex is /pattern/flags. In our example, the regex is the /[aeiou]/gi.

pattern is the text of the regular expression. In the above example, the [aeiou] , the vowels we are looking for, is our pattern. The pattern itself is actually aeiou, but note that patterns are always wrapped in brackets.

flags are added to specify the parameters of the search pattern. In the above, the g flag says to find all matches within the string (as opposed to just the first), and the i flag says to ignore the case of the letters.

There are also certain special characters that can be added to pattern that help with search logic. The ^ , placed at the front of a pattern, negates the search pattern. For example, [^aeiou] would match all letters that are not vowels. Check out the Docs for a full breakdown of all the characters.

.match() is a Javascript method that matches a string against a regular expression. It returns an array with the first complete match, unless the g flag is used, in which case it returns all matches. In the above, to see how many characters in the string matched a vowel, we therefore just needed to return the length of that array.

Some useful examples

Regex is good for more than efficiently solving problems you’ll only see in technical interviews, it’s a powerful tool in the real world as well.

Regex has some special character classes that help shorten some of the work of building out your own unique regex. For example, /\d/ which matches any digit, is the same as /[0-9]/ . Another useful one is /\w/, which matches any number or letter, as well as underscores. Again, I highly recommend taking a look at the Special characters tab in the Docs to see all the possibilities.

Say a special troll, or more likely a technologically confused human, tries to put in a number value inside your ‘First Name’ input field. You could validate that input with the following regex:

function validFirstName(userInput){
if(userInput.match(/[^a-z]/gi){
console.log("User input is invalid")
} else {
console.log("User input is valid")
}
}

In another example, the following could help you extract the pure numeric value of dollar string.

function getMoneyValues(moneyString){
return moneyString.match(/[^$]/g).join('')
}
//getMoneyValues('$14.95')
//-->'14.95'

E-mail validation is another great place to use regular expressions. If the construction of that sounds complicated to you, then you’re right. If you think a simple Google search will take you to regex someone already built for that exact purpose, you are also right.

I hope some of the uses of regex are more clear to you now, and that you are de-intimidated from continuing your regular expression journey. Check out some of the resources below for further instructions, and have fun experimenting!

--

--