What is regex?
What is it used for?
Regex is used for various reasons. You can use regex if you are trying to locate, add characters in a sentence. Another way to use them is to test if certain characters are in a text or sentence. The literal notation form is used when our expressions remain constant and won’t be changed. For example, we can declare a regex outside of a loop to use for each iteration. The constructor function form is used when your expression pattern will be changing or if you don’t know the incoming pattern that is coming from the user input. For example, if you want to test if certain characters are in a text and you do not know what the incoming characters are, the constructor is best used.
How do you use regex?
In the snippet above, we test to see if our string contains the word ‘to’. On line 1, we declare a variable named sentence1 with a const keyword and assign it a string value of “Hello I like to be happy.” On line 2, we declare another variable named sentence2 with a const keyword and assign it a string value of “Hello I am happy.”. On line 4, we declare a variable named literalRegex and assign it a value of a regex literal pattern /to/. On line 6, we use the test method to check if our sentence1 string contains the word “to” if so the console will log true. On line 7, we use the test method again to check if our sentence2 contains the word ‘to’. Since our string does not contain the word ‘to’, the console will log false.
In the snippet, above we also test to see if our string contains the word “to”. On line 1, we declare a variable named sentence1 with a const keyword and assign it a string value of “I like to be happy”. On line 2, we declare a variable named sentence2 with a const keyword and assign it a string value of “I am happy”. On line 6, we declare a variable named con and assign it a value of a construction function pattern with parenthesis and two patterns where we use a quantifier after our “to” word followed by the g flag. The quantifier will check if the word “to” appears once or more. The g flag will make it a global search so that means it won’t stop after the first match. On line 8 we test to check if our sentence1 string value contains the word “to”. Since it does the console logs true. On line 9, we test to check if our sentence2 string value contains the word “to”. Since it does not, the console will log false.