Hello, welcome to my blog
This is my first ever blog post, apologies if it doesn't look like others you must have come across.
This blog post will be a series of three parts, the first part will cover the basics on regular expression and some methods available to be used with regular expression, the second section will cover character sets available in Regular Expressions, these character sets are what regular expressions are all about, they can be likened to the grammar of the language.
In the final section, we will be implementing Regular expressions on a simple signup form. It will be a long read, but I promise to make it fun for us all.
Grab some popcorn and ice cream as we go on the Regular Expressions Journey together.
Have you tried filling a form online and you get responses like "Enter a valid email address" or "password must contain alphanumeric characters"?. The mechanism behind this type of response you get most times is as a result of regular expressions being implemented.
In simple terms, a regular expression or RegExp can be described as a series of characters following with a following a defined syntax that can be used to check for the existence of a particular pattern in a different data type.
Declaring Regular Expressions
In JavaScript, regular expressions can be described in two ways
- Using the RegExp constructor
- Using the RegExp pattern i.e two forward slashes, with strings declared in single or double quotes and at times in backticks
Regular expressions parameters
A regular expression can take in two parameters. The first parameter is the pattern that is to be matched while the second parameter is a flag which is sometimes optional
Patterns
A pattern can be described as a word, string of text or numbers that we intend to match from within a given piece of data. Patterns can be anything from a simple /JavaScript/
text to more complex expressions like /[a-zA-Z0-9]/
.
Flags
As I described above flags are not compulsory parameters, but they determine the type of match to be made, though optional they are really important. examples of flags are
- i: when used it means matches patterns that are both lowercase and uppercase, it simply means case insensitive.
- g: this is a global flag and it looks for a pattern to match within the whole text that is being searched.
Don't worry if these flags are not clear yet, they will be discussed in detail later.
Creating RegExp patterns
We would recall that we said Regular expressions can be described using constructor and the regexp pattern. We will be creating our first expressions using a constructor.
Creating patterns with Constructor
// without flag
let pattern = 'javascript';
let regEx = new RegExp(pattern);
The above expression is a way of declaring regExp without flags using the constructor.
Now, let's try to describe another still using the constructor, but now with global and case insensitive flag
let pattern = 'javascript';
let flag = 'gi';
let regEx = new RegExp(pattern, flag);
This can be declared in a short form as
let regEx = new RegExp('javascript', 'gi');
Creating a pattern without RegExp Constructor
Declaring a regular expression without a constructor is easy as it only requires the expression/string being tested for to be placed between two forward slashes followed by flag(s) which is/are optional as discussed earlier. The expression below shows a typical example of how to make a regular expression statement without the use of a constructor.
let regEx = /javascript/gi;
The above expression is the same as the regExp that we have described above using the constructor.
let regEx = new RegExp('javascript', 'gi');
RegExp Object Methods
Just the way we can declare RegExp there are also methods that can be called on RegExp methods. Let us check out some of these methods
Test
test(): This method tests for matches in a string, it checks if the pattern declared matches any of the string in the list of data being tested, and then returns a boolean.
Let's examine the example below
const str = 'Javascript is fun!';
const pattern = /Javascript/; // RegExp declared with pattern
const result = pattern.test(str);
console.log(result);
The result
true
Match
Match(): The match method when used returns an array of all matches in the string being tested and returns null when no match is found. When a global flag is not used, the global flag returns not just the match but also the pattern declared, its index, length and the group.
Let us examine a simple example below
const str = 'JavaScript is fun!';
const pattern = /JavaScript/;
const result = str.match(pattern);
console.log(result);
The result
[0: "JavaScript", groups: undefined, index: 0, input: "JavaScript is fun!"]
Let's use the match method again together with the global flag g to see if a pattern matches a string.
const str = 'JavaScript is fun!';
const pattern = /JavaScript/g;
const result = str.match(pattern);
console.log(result);
The result
["JavaScript"]
Search
Search(): This method tests for the match of a pattern in a string. It returns the index of the string if there exists a match, if not it returns -1.
Replace
replace() : The replace method takes in two parameters, the pattern to be matched and another string that the eventually matched string will be replaced with. It can simply be said that the method executes a search for a string and replaces the matched substring with a replacement substring.
let text = 'I love Go, it is an awesome language'
let newText = text.replace(/Go|go/, "JavaScript")
console.log(newText)
The result
I love JavaScript, it is an awesome language
But, what if there exists more than a single GO string within the text, will all the GO string be replaced? The answer is No!. This is because there was no flag declared. The Replace method will only search through the text, match the first string that corresponds with the pattern and then ignores the others, even if those strings match the declared pattern.
To avoid this we can set declare the global flag on the patter and also add the case insensitive flag so it matches every string within the text without any preference for the case.
Let's see a typical example below
const txt =
'Golang is the most beautiful language that a human being has ever created.\
I recommend Golang for its fast execution and ease of programming';
newText = txt.replace(/Golang/gi, 'JavaScript');
console.log(newText);
The result
JavaScript is the most beautiful language that a human being has ever created. I recommend JavaScript for its fast execution and ease of programming
That will be all for this part, in the next part, we will cover some of the character sets available in Regular Expressions. Thanks for following the post till the end.
I'd like to appreciate @MaryanneOnuoha for inspiring me to give this a shot, also for her help in helping to proofread and making some edits.
Thank you also for following this article to the end, I know its quite a long read, I'd love to know your thoughts in the comment section.
You can also follow me to know when the other parts are released.