using regex Flashcards
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 returns true or false if your pattern finds something or not.
let testStr = “freeCodeCamp”;
let testRegex = /Code/;
testRegex.test(testStr);
inser the string you are looking for inside of the forward slashes
you can search for multiple words by using the OR operator within the forward slashes
for example /dog|cat|bird/
Write a regex fccRegex to match freeCodeCamp, no matter its case. Your regex should not match any abbreviations or variations with spaces.
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 case - the i flag. You can use it by appending it to the regex. An example of using this flag is /ignorecase/i. This regex can match the strings ignorecase, igNoreCase, and IgnoreCase.
To use the .match() method, apply the method on a string and pass in the regex inside the parentheses.
“Hello, World!”.match(/Hello/);
let ourStr = “Regular expressions”;
let ourRegex = /expressions/;
ourStr.match(ourRegex);
Sometimes you won’t (or don’t need to) know the exact characters in your patterns. Thinking of all words that match, say, a misspelling would take a long time. Luckily, you can save time using the wildcard character: .
The wildcard character . will match any one character. The wildcard is also called dot and period. You can use the wildcard character just like any other character in the regex. For example, if you wanted to match hug, huh, hut, and hum, you can use the regex /hu./ to match all four words.
let humStr = "I'll hum a song"; let hugStr = "Bear hug"; let huRegex = /hu./; huRegex.test(humStr); huRegex.test(hugStr);
Using the hyphen (-) to match a range of characters is not limited to letters. It also works to match a range of numbers.
let jennyStr = “Jenny8675309”;
let myRegex = /[a-z0-9]/ig;
jennyStr.match(myRegex);
You can search for whitespace using \s, which is a lowercase s. This pattern not only matches whitespace, but also carriage return, tab, form feed, and new line characters. You can think of it as similar to the character class [ \r\t\f\n\v].
let whiteSpace = “Whitespace. Whitespace everywhere!”
let spaceRegex = /\s/g;
whiteSpace.match(spaceRegex);
You can search for non white space with \S