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.
- 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
theword the in the string
The dog chased the cat, you could use the following regular expression:
/the/. Notice that quote marks are not required within the regular expression.
.test()method takes the regex, applies it to a string (which is placed inside the parentheses), and returns
falseif your pattern finds something or not.
let myString = "Hello, my name is Randy."; let myRegex = /Hello/; let result = myRegex.test(myString)
console.log(result); will display true
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
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.
- You can search for multiple patterns using the
|. This operator matches patterns either before or after it. For example, if you wanted to match the strings
no, the regex you want is
- You can also search for more than just two patterns. You can do this by adding more patterns with more
ORoperators separating them, like
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;