Regular Expressions in JavaScript
An overview of RegEx and tips on how to write expressions for beginners
In this article, I will explain the fundamentals of what a regular expression is, basic rules to create a simple one, and some general tips from my experience. And as a result, you can create your own without needing to dig through Google.
Like most developers, whenever I have a task that could be completed by a simple RegEx, I will start Google searching for patterns that match my needs. Then as the project develops, the validation needs updating, and my previous pattern no longer works. I need to search again and take a lot of time to find the right one.
This cycle made me realize I need to master these myself so I can generate my own RegEx without needing Google’s help.
For more content like this, check out https://betterfullstack.com
What is a Regular Expression
Regular Expressions is simply a way to describe a pattern in string data.
How to create a new one
There are two ways to create a RegExp:
- Use the RegExp constructor:
const sample = new RegExp('sample');
- Written as a literal value by enclosing a pattern in forward slash (
/
) characters:const sample = /sample/;
Note:
- Some characters, such as question marks
?
and plus signs+
have special meanings in regular expressions and MUST be preceded by a backslash`
if you want to match the character directly. The backslash escapes the character. Example:const sample = /sample\+/;
- A regular expression is a type of object
typeof sample // "object"
. - A regular expression consists of non-special characters.
How to use RegEx
Use test()
to test the string: sample.test("sample project");
This method will return a boolean
value that lets you know if the string matches the expression’s pattern.
Another function is the exec()
method. It will return null
if no match was found and return an object with information about the match…