An Interest In:
Web News this Week
- March 3, 2024
- March 2, 2024
- March 1, 2024
- February 29, 2024
- February 28, 2024
- February 27, 2024
- February 26, 2024
April 19, 2022 11:19 am GMT
Original Link: https://dev.to/hambalee/regular-expression-example-4pp3
Regular Expression Example
let myStr = "Hello World!"let myRegex = /Hello/myRegex.test(myStr) // truelet myRegex2 = /hello/ myRegex2.test(myStr) // falselet myRegex3 = /hello/i myRegex3.test(myStr) // truemyStr.match(myRegex) // "Hello"let myStr2 = "Hello World! hello"let myRegex4 = /Hello/igmyStr2.match(myRegex4) // ["Hello,"hello"]
Match Anything with Wildcard Period
let humStr = "I'll hum a song";let hugStr = "Bear hug";let huRegex = /hu./;huRegex.test(humStr); // truehuRegex.test(hugStr); // true
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
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' ]
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
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' ]
Match Numbers and Letters of the Alphabet
let jennyStr = "Jenny8675309";let myRegex = /[a-z0-9]/ig;jennyStr.match(myRegex);
let quoteSample = "Blueberry 3.141592653s are delicious.";let myRegex = /[h-s2-6]/ig;let result = quoteSample.match(myRegex);
Match Single Characters Not Specified
let quoteSample = "3 blind mice.";let myRegex = /[^aeiou0-9]/ig;let result = quoteSample.match(myRegex);
Match Characters that Occur One or More Times
let difficultSpelling = "Mississippi";let myRegex = /s+/g;let result = difficultSpelling.match(myRegex);//[ 'ss', 'ss' ]
Match Characters that Occur Zero or More Times
let chewieQuote = "Aaaaaaaaaaaaaaaarrrgh!"let chewieRegex = /Aa*/;let result = chewieQuote.match(chewieRegex); // ['Aaaaaaaaaaaaaaaa']
Original Link: https://dev.to/hambalee/regular-expression-example-4pp3
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To