Regular Expressions Flashcards
Name the String methods that work with RegEx patterns:
match, replace, search, split
Make pattern for finding all numbers that are two or more digits (e.g. will find 10 and 333 but not 3 in “3 333 10”)
/\d{ 2, }/g – escape d; comma says a number to or more digits.
Make a pattern for finding the first letter in every word of a sentence.
/^[a-zA-Z]|\s[a-zA-Z]/g; ^ says find any letter at start of sentence; | says ‘or’ and \s says whitespace preceeding any letter.
what are the RegEx flags supported by js?
g for global, i for ignore case, and m for multiline
What is the literal for finding if a string contains 3 digits in a row?
/\d{3}/;
or /[0-9][0-9][0-9]/
Note: this will be true for “123” as well as “1234” but not “12”
If you simply want to know if a string has an @ with characters on either side, do what?
mystring.search( /[a-zA-Z]@[a-zA-Z]/ ); // returns -1 if nothing found; otherwise, returns index of first location.
what is the syntax for the replace() method?
nameOfString.replace(patternToMatch, replaceWith);
What does the question mark do?
Preceding character is optional. Matches 0 or 1 occurrence. Pattern colou?r will match color or colour. Pattern belle? will match bell or belle.
What does [XYZ] do?
Matches any single character from the character class. [ch]at will match cat and hat but not at.
Match a pattern only if it occurs at beginning of string with what character?
Match a pattern only if it occurs at end of string with what character?
$
Match anything that’s NOT a letter (not a, b, c, A, B, etc)
[^a-zA-Z]
Match the word ‘hello’ ONLY if it’s the only content in a string. Match “hello” but not “ hello” or “yo, hello”.
/^hello$/
Search for the words “image” or alttext” or “classname”
/image|alttext|classname/g
What arguments does the string.replace() function take and how do they work?
Arg1 is the pattern. Arg2 is the replacement string or else a function that takes the match (and additional arguments as well) and returns a string.