let myStr = " Hello World! "
let myRegex = /Hello/
myRegex . test ( myStr ) // true
let myRegex2 = /hello/
myRegex2 . test ( myStr ) // false
let myRegex3 = /hello/i
myRegex3 . test ( myStr ) // true
myStr . match ( myRegex ) // "Hello"
let myStr2 = " Hello World! hello "
let myRegex4 = /Hello/ig
myStr2 . match ( myRegex4 ) // ["Hello,"hello"]
Enter fullscreen mode
Exit fullscreen mode
Match Anything with Wildcard Period
let humStr = " I'll hum a song " ;
let hugStr = " Bear hug " ;
let huRegex = /hu./ ;
huRegex . test ( humStr ); // true
huRegex . test ( hugStr ); // true
Enter fullscreen mode
Exit fullscreen mode
Match Single Character with Multiple Possibilities
let bigStr = " big " ;
let bagStr = " bag " ;
let bugStr = " bug " ;
let bogStr = " bog " ;
let bgRegex = /b [ aiu ] g/ ;
bigStr . match ( bgRegex ); // ["big"]
bagStr . match ( bgRegex ); // ["bag"]
bugStr . match ( bgRegex ); // ["buig"]
bogStr . match ( bgRegex ); // null
Enter fullscreen mode
Exit fullscreen mode
let quoteSample = " Beware of bugs in the above code; I have only proved it correct, not tried it. " ;
let vowelRegex = / [ aeiou ] /ig ;
let result = quoteSample . match ( vowelRegex );
// [ 'e', 'a', 'e', 'o', 'u', 'i', 'e', 'a', 'o', 'e', 'o', 'e', 'I', 'a', 'e', 'o', 'o', 'e', 'i', 'o', 'e', 'o', 'i', 'e', 'i' ]
Enter fullscreen mode
Exit fullscreen mode
Match Letters of the Alphabet
let catStr = " cat " ;
let batStr = " bat " ;
let matStr = " mat " ;
let bgRegex = / [ a-e ] at/ ;
catStr . match ( bgRegex ); //["cat"]
batStr . match ( bgRegex ); //["bat"]
matStr . match ( bgRegex ); //null
Enter fullscreen mode
Exit fullscreen mode
let quoteSample = " The quick brown fox jumps over the lazy dog. " ;
let alphabetRegex = / [ a-z ] /ig ;
let result = quoteSample . match ( alphabetRegex ); //[ 'T', 'h', 'e', ... ,'d', 'o', 'g' ]
Enter fullscreen mode
Exit fullscreen mode
Match Numbers and Letters of the Alphabet
let jennyStr = " Jenny8675309 " ;
let myRegex = / [ a-z0-9 ] /ig ;
jennyStr . match ( myRegex );
Enter fullscreen mode
Exit fullscreen mode
let quoteSample = " Blueberry 3.141592653s are delicious. " ;
let myRegex = / [ h-s2-6 ] /ig ;
let result = quoteSample . match ( myRegex );
Enter fullscreen mode
Exit fullscreen mode
Match Single Characters Not Specified
let quoteSample = " 3 blind mice. " ;
let myRegex = / [^ aeiou0-9 ] /ig ;
let result = quoteSample . match ( myRegex );
Enter fullscreen mode
Exit fullscreen mode
Match Characters that Occur One or More Times
let difficultSpelling = " Mississippi " ;
let myRegex = /s+/g ;
let result = difficultSpelling . match ( myRegex );
//[ 'ss', 'ss' ]
Enter fullscreen mode
Exit fullscreen mode
Match Characters that Occur Zero or More Times
let chewieQuote = " Aaaaaaaaaaaaaaaarrrgh! "
let chewieRegex = /Aa*/ ;
let result = chewieQuote . match ( chewieRegex ); // ['Aaaaaaaaaaaaaaaa']
Enter fullscreen mode
Exit fullscreen mode
Top comments (0)