Web Development Course:
- A regular expression is a string of text that makes a search pattern. It is formed using specific rules.
- A regular expression can be a simple word or a complex pattern.
- RegEx is a common abbreviation for regular expressions.
Let's say we have
/learn/i as our regular expression.
learn is a search pattern.
i is a modifier of the regular expression (it makes the search case-insensitive):
var reg = /learn/i;
Using String Methods
Regular expressions are usually used with these two string methods:
replace(). We will now review both of them in more detail.
"Learn" string because the
i modifier specifies the search to be case-insensitive:
var text = "Learn computers"; var re = text.search(/learn/i);
search() method also accepts strings as arguments:
var text = "Learn computer things today!"; var str = text.search("computer");
"books" is replaced with a string
var text = "Books are the best."; var re = text.replace(/books/i, "Movies");
var text = "The best food is sushi."; var re = text.replace("sushi", "pizza");
Patterns and Modifiers
Whenever we need to find a range of characters, we use brackets. They can be round and square, depending on the situation:
|[abc]||True if any of the characters in brackets is found|
|[0-9]||True if any of the numbers in brackets is found (can be specified in intervals)|
|(x|y)||True if any of the alternatives separated by | symbol is found|
Characters that have a special meaning are called metacharacters. Let's see them in a table to get a better idea:
|\d||True if any number is found|
|\s||True if a whitespace character is found|
|\uxxxx||True if a character which is specified by a hexadecimal code is found|
As the name itself tells us, quantifiers are used to define quantities:
|n+||If a string contains at least one n, it's a match|
|n*||If a string has zero or more of n, it's a match|
|n?||If a string contains zero or one of n, it's a match|
Now, modifiers are not patterns. However, they are very important to them, as they change the way a pattern is searched. Review the table to get a better idea how they affect the search:
|i||Performs case-insensitive search|
|m||Performs multiline matching|
Using RegEx Object
First and foremost, the RegEx object has a
test() method. It searches a defined string for a specified pattern and returns
The example below searches for an
x character in a specified string:
/a/.test("Things should always be learned from abc to xyz");
exec() is also a RegEx object method. Using it, the text you searched for is returned. The code is the example below is again used to look for an
x character, but the return value is different:
/x/.exec("The letter a usually goes before the letter x");
- A regular expression allows you to create search patterns with specific rules.
- RegEx are made of modifiers and patterns. Patterns are comprised of brackets, metacharacters, and quantifiers.