Regular expressions are patterns used to match and/or manipulate strings. This is a high-level overview of a few of the practical applications of a RegEx in Javascript.
What is RegEx and what’s it doing in Javascript?
A RegEx consists of simple and special characters that together form a language of its own. Regular expressions can be used to match strings, identify specified patterns, and extract parts of strings.
RegEx is a common enough function available in programming languages. They provide powerful ways to recognize patterns and test a given string efficiently and quickly.
Regular expressions are easy to get started with but can get difficult quickly. Regular expressions can be notorious to decipher, hard to understand and in general, and become an object of your nightmares if not properly tested.
RegEx is an object in Javscript. Since Javascript was primarily manipulating HTML and content, it directly supports RegEx, gets a dedicated RegEx notation and, expectedly, makes it easy to deal with strings.
Ways to create RegEx
There are two ways to create RegEx -
- The most common way
|
|
- The obnoxious way
|
|
By itself RegEx just describes a pattern. You may apply that pattern to a string using Javascript methods. For example, .test
tests whether the defined pattern exists in the given string.
|
|
Types of Methods using RegEx
You can use more than one type of function with RegEx.
Identify / search
Identify a string pattern within a given string.
|
|
Or, use a string expression. I find this easier to remember since I start with strings most of the time.
|
|
Search with additional info
Search a given string, but also potentially do something with the extracted strings.
Use RegEx.
|
|
As in the previous case, alternatively use string expressions.
|
|
You can boost up the power by using flags in RegEx.
|
|
And then, level up even more using range manipulation.
|
|
Manipulate
Use RegEx to split a string.
|
|
Or, replace a substring within string.
|
|
Few examples of practical application of RegEx
Here are a few common examples of how RegEx is used.
Test valid email
Test whether a given string is a valid email.
|
|
Test names
Test whether the name input by user is correct.
The below pattern does not accept numbers or special characters. Depending on the region you are in, you may need to change the pattern to accept special characters and numbers.
|
|
Tools to Learn RegEx
As you may have seen by now, RegEx is a beast of its own. I do two things to speed up my application of RegEx -
- Google - for e.g. search for
email validation regex
- Use external tools to iterate through RegEx quickly before deciding the final pattern
Some of the tools that are super useful -
- [https://regexr.com/]: See a visual representation of RegEx application in Javascript and PHP
- [https://regex101.com]: a clean way to quickly test regular expressions in Javascript, PHP, Python and Go