In this article, we will explore some characters, a few shortcuts, and the common uses for writing regular expressions.
Regular expressions are used in programming languages to match parts of strings.
let testStr = "hello world"; let testRegex = /hello/; testRegex.test(testStr); // Returns true
As you can see, it returns true because the regex is available in our string.
In the previous example, we used the test method to search for words in a string. Here’s another example searching for a literal match of the string
let testStr = "Hello, my name is Kevin."; let testRegex = /Kevin/; testRegex.test(testStr); // Returns true
Notice that, any other forms of the string
"**K**evin" will not match. For example, the regex
/**K**evin/ will not match
"**KEVIN**". That will return false.
let wrongRegex = /KEVIN/; wrongRegex.test(testStr); // Returns false
As you can see in the last example, to match literal strings we should have the same letter case (uppercase & lowercase). But sometimes, you might want to also match case differences. You can match both cases using what is called a flag. There are other flags but here you’ll focus on the flag that ignores the case-the i flag. You can use it by appending it at the end of the regex.
let testStr = "Hello, my name is KEVIN."; let testRegex = /Kevin/i; // the i flag. testRegex.test(testStr); // Returns true
As you can see, even though we have a case difference(KEVIN & Kevin), it returns true because we used the i flag.
You can also extract the actual matches you found with the method .match(). Here’s an example:
"Hello, World!".match(/Hello/); // Returns ["Hello"] let ourStr = "Regular expressions"; let ourRegex = /expressions/; ourStr.match(ourRegex); // Returns ["expressions"]
Note that the syntax
.match is the "opposite" of the method
.test you have been using:
We can find more than one match in a string. To achieve that, we will need to use the gflag by appending it at the end of the regex. Have a look at the following examples:
let testStr = "Repeat, Repeat, Repeat"; let ourRegex = /Repeat/; testStr.match(ourRegex); // Returns ["Repeat"]
Using the g flag:
let repeatRegex = /Repeat/g; testStr.match(repeatRegex); // Returns ["Repeat", "Repeat", "Repeat"]
As you can see, we can search or extract a pattern more than once using the g flag.
With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...
You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...