Regular expressions are patterns that help programmers match, search, and replace text.
In these upcoming posts, you'll learn how to use special characters, capture groups, positive and negative lookaheads, and other techniques to match any text you want.
Using the test method
- Regular expressions are used in programming languages to match parts of strings. You create patterns to help you do that matching.
Let's say you want to find
the
word the in the stringThe dog chased the cat
, you could use the following regular expression:/the/
. Notice that quote marks are not required within the regular expression.JavaScript has multiple ways to use regexes. One way to test a regex is using the
.test()
method. The.test()
method takes the regex, applies it to a string (which is placed inside the parentheses), and returnstrue
orfalse
if your pattern finds something or not.Ex:
let myString = "Hello, my name is Randy.";
let myRegex = /Hello/;
let result = myRegex.test(myString)
console.log(result); will display true
Matching Literal Strings
Above, you searched for the word Hello
using the regular expression /Hello/
. That regex searched for a literal match of the string Hello
. Here's another example searching for a literal match of the string Randy
:
let myStr = "Hello, my name is Randy.";
let myTestRegex = /Randy/;
let result = myTestRegex.test(myStr);
console.log(result); will display true
- Note: Any other forms of Randy will not match. For example, the regex /Randy/ will not match randy or RANDY.
Matching a Literal String with Different Possibilities
- You can search for multiple patterns using the
alternation
orOR
operator:|
. This operator matches patterns either before or after it. For example, if you wanted to match the stringsyes
orno
, the regex you want is/yes|no/
. - You can also search for more than just two patterns. You can do this by adding more patterns with more
OR
operators separating them, like/yes|no|maybe/
. - Ex:
let petString = "Alan had a pet dog.";
let petRegex = /dog|cat|bird|fish/;
let result = petRegex.test(petString);
console.log(result); will display true;
- Your regex petRegex should return false for the string Emma has a pet rock.
let petString = "Emma has a pet rock.";
let petRegex = /dog|cat|bird|fish/;
let result = petRegex.test(petString);
console.log(result); will display false;
Top comments (0)