Regular expressions can be hard to understand and difficult to learn. However, they are extremely powerful and have many use cases in the real world. In this post, I will explore some practical applications of regex.
Form Field Validation
One of the most common use cases for regex is validating form fields such as emails, usernames, credit card numbers, phone numbers, dates, password strength, etc.
The following example is a regex that validates the format of an email.
const emailValidatorRegex = /^[^@\s]+@[^@\s]+\.[^@\s\.]{2,}$/
function isValid(email) {
if emailValidatorRegex.test(email) {
return true
} else {
return false
}
}
isValid('dummyemail@gmail.com') // true
isValid('dummyemail@gmail') // false
Find and Replace
Regex can be used to write complex find and replace functions. You can even use regex to find and replace inside editors like VSCode.
The following example takes all normal javascript function declarations and replaces them with arrow functions.
const normalFunction = `
function add(x, y) {
return x + y
}
`
const arrowFunction = normalFunction.replace(/function\s*(\w+)\s*\(([^\)]+)\)/g, "const $1 = ($2) =>")
console.log(arrowFunction)
/*
const add (x, y) => {
return x + y
}
*/
Here is how you could use this to find and replace in VSCode.
HTML Parsing
Another use case for regex is for parsing things like HTML. Maybe you want to extract image sources from some HTML or extract all the URLs from a Google search result.
Let's say you have some HTML, and you want to extract everything that is inside of an <li>
and put it into an array. Here's how we could do this.
const markup = `
<html>
<body>
<h1>Shopping List</h1>
<h2>Produce</h2>
<ul>
<li>Celery</li>
<li>Apples</li>
</ul>
<h2>Frozen</h2>
<ul>
<li>Ice Cream</li>
<li>Hot Pockets</li>
</ul>
</body>
</html>
`
const listParser = /(?<=<li>)(\w|\s)+(?=<\/li>)/gm
const shoppingList = markup.match(listParser)
console.log(shoppingList)
// [ 'Celery', 'Apples', 'Ice Cream', 'Hot Pockets' ]
Conclusion
There is so much you can do with regular expressions. However, they are definitely not the solution to everything. Despite their power and flexibility, they are not the most readable for other developers.
Maybe don't reach for it for something like trimming whitespace from a string. There are string methods or basic functions for this. But for complex search, find and replace, validation, and parsing, regular expressions are a great solution. Plus, they are fun to write!
Want to learn regex?
Check out my interactive course: https://www.slip.so/courses/regular-expresssions-in-javascript
Follow me on Twitter for updates: https://twitter.com/katherinecodes
Top comments (0)