Let's connect on LinkedIni -> Otwoma Dennis
Using the match method
letsentence="The dog chased the cat";letregex=/the/;letresult=regex.test(sentence);console.log(result);//trueMatch literal strings
letwaldoIsHiding="Somewhere waldo is hiding in this text.";letwaldoRegex=/Waldo/;letresult=waldoRegex.test(waldoIsHiding);console.log(result);//false due to Waldo and not waldoMatch a literal string with different possibilities
regex has an or operator which is a single pipe character. If any of the provided possibilites is in the literal string, the test returns true.
letpetString="James has a pet cat, bird and dog";letpetRegex=/dog|cat|fish/;letresult=petRegex.test(petString);console.log(result);//returns true even though fish is not thereIgnore case while matching
We can provide a flag to match both upper and lowercase.
The i flag ignores case.
letmyName="Dennis The Great";letmyRegex=/dennistheGreat/i;letresult=myRegex.test(myName);console.log(result);//trueExtract matches
So far, we have been checking if a pattern exists in a string or not.
We can also extract the matches we find with the match method.
letextractStr="Extract the word coding from this String";letcodingRegex=/coding/;letresult=extractStr.match(codingRegex);console.log(result);//["coding"]Find more than the first match
We can search and extract a pattern more than once using the g flag
lettestStr="Jack, Jack, Jack and zaph";letourRegex=/Jack/g;letresult=testStr.match(ourRegex);console.log(result);//[ 'Jack', 'Jack', 'Jack' ]i and g flag working together
lettwinkleStar="Twinkle twinkle little star";letregex=/twinkle/gi;letresult=twinkleStar.match(regex);console.log(result);//[ 'Twinkle', 'twinkle' ]Match anything with the wildcard period
In regex, a period is a wildcard character, it can stand for anything.
lethumStr="I'll hum a song and hug a bear then run to the hut.";lethugRex=/hu./g;//will take everything starting with huletresult=humStr.match(hugRex);console.log(result);//[ 'hum', 'hug', 'hut' ]matching anything that ends with un and starts with any other letter using the wildcard period
letexampleStr="let's run and have fun but not with the gun and the trun";letunReg=/.un/g;letresult=exampleStr.match(unReg);console.log(result);//[ 'run', 'fun', 'gun' ]Match single character with multiple possiblities
We can also match from a predefined group of characters.
letbgStr="Beware of the big bug in your bag but don't beg.";letbgRegex=/b[aeiu]g/g;letresult=bgStr.match(bgRegex);console.log(result);//[ 'big', 'bug', 'bag', 'beg' ]Match letters of the alphabet
letquoteSample="The quick brown fox jumped over the lazy dog";letalphabetRegex=/[a-z]/gi;letresult=quoteSample.match(alphabetRegex);console.log(result);//['T', 'h', 'e', 'q', 'u', 'i', 'c','k', 'b', 'r', 'o', 'w', 'n', 'f','o', 'x', 'j', 'u', 'm', 'p', 'e','d', 'o', 'v', 'e', 'r', 't', 'h','e', 'l', 'a', 'z', 'y', 'd', 'o','g']Match numbers and letters of the alphabet
letlettersNumbersStr="The holy value of pi is 3.141592653, isn't it?";letletsNumsRegex=/[2-6h-s]/gi;//matching the digits 2-6 and letters h-s in the stringletresult=lettersNumbersStr.match(letsNumsRegex);console.log(result);//['h', 'h', 'o', 'l', 'l','o', 'p', 'i', 'i', 's','3', '4', '5', '2', '6','5', '3', 'i', 's', 'n','i']Match single characters not specified
We can also create a set of characters that we DON'T want to match
These are called negated charater sets and they are created with the caret character ^ Watch How to Train Your Dragon Homecoming (2019).mp4 Watch How to Train Your Dragon Snoggletog Log (2019).mp4 Watch Riverdance The Animated Adventure (2021).mp4
//Matching everything except all numbers and all vowelsletrmString="3 blind mice";letrmRegex=/[^0-9aeiou]/gi;letresult=rmString.match(rmRegex);console.log(result);//[' ', 'b', 'l', 'n', 'd', ' ', 'm','c']Match characters that occur one or more times
We can check if a character occures one or more times using the + character
letdifficultSpelling="Mississippi";letregex=/s+/g;letresult=difficultSpelling.match(regex);console.log(result)// [ 'ss', 'ss' ]Match characters that occure zero or more times
There is an option to match characters that occur zero or more times.
we use the * character to match zero or more times
letsoccerWord="goooooooal!";letgPhrase="gut feeling";letoPhrase="over the moon";letgoRegex=/go*/;console.log(soccerWord.match(goRegex))// ['gooooooo']console.log(gPhrase.match(goRegex))// ['g']console.log(oPhrase.match(goRegex))// nullFind characters with lazy matching
Greedy match finds the longest possible part of the string that matches the pattern and returns it as a match.
Lazy match finds the smallest possible part of the string and returns that.
Regex patterns default to greedy, i.e they find the longes match and return it.
We use a question mark to define a lazy match.
letstring="titanic";letgreedyDefaultRegex=/t[a-z]*i/;letlazyRegex=/t[a-z]*?i/;console.log(string.match(greedyDefaultRegex));// ['titani'] --> longest possible matchconsole.log(string.match(lazyRegex));// ['ti'] --> has returned shortest possible matchlettext="<h1>Winter is coming </h1>";//we want to match the first <h1> onlyletmyRegex=/<.*?>/;letresult=text.match(myRegex);console.log(result);// ['<h1>']A group of criminals escaped from jail and ran away, you don't know how many but you do know that they do stay together when they are around other people., you are responsible for finding all the criminals at once, the criminals are respresented by a c. Your task is to write a regex that will match anytime there is one or more c's. in the string that is passed in.
letcrowd="P1P2P3P4P5P6CCCP7P8P9";letreCriminals=/./;letmatchedCriminals=crowd.match(reCriminals);console.log(matchedCriminals);letcrowd="P1P2P3P4P5P6CCCP7P8P9";letreCriminals=/c+/gi;letmatchedCriminals=crowd.match(reCriminals);console.log(matchedCriminals);Match beginning string patterns
You can match patterns that are only at the begginning of a string.
The caret ^ character inside a character set [^] is used to create a negated character set.
If we are not in the character set, we can use the caret to only match at the beginning of a string.
letrickyAndCal="Cal and Ricky both like racing";letcalRegex=/^Cal/;letresult=calRegex.test(rickyAndCal);console.log(result);//trueMatch ending string patterns
Caret matches the beginning string pattern and a dollar sign ($) matches an ending string pattern.
letcaboose="The last car on the train is a caboose";letlastRegex=/caboose$/;letresult=lastRegex.test(caboose);console.log(result);//trueMatch all letters and numbers
\w is used to match the a-z A-Z 0-9 and underscore
letquoteSample="The 5 boxing wizards jump quickly.";letalphabetRegex=/\w/g;letresult=quoteSample.match(alphabetRegex);console.log(result);// ['T', 'h', 'e', '5', 'b', 'o', 'x', 'i', 'n', 'g', 'w', 'i', 'z', 'a', 'r', 'd', 's', 'j', 'u', 'm', 'p', 'q', 'u', 'i','c', 'k', 'l', 'y']Match everything except letters and numbers
\W (uppercase w) will match anything that is not a letter, a number or an underscore.
letquoteSample="The 5 boxing wizards jump quickly.";letnonAlphabetRegex=/\W/g;letresult=quoteSample.match(nonAlphabetRegex);console.log(result);// [ ' ', ' ', ' ', ' ', ' ', '.' ]Match all numbers
\d matches digits only.
letnumString="Your sandwich will cost $5.00";letnumRegex=/\d/g;letresult=numString.match(numRegex);console.log(result);//['5', '0', '0']Match all non-numbers
\D will match all non-numbers.
letnumString="Your sandwich will cost $5.00";letnumRegex=/\D/g;letresult=numString.match(numRegex);console.log(result);//['Y', 'o', 'u', 'r', ' ', 's', 'a', 'n', 'd', 'w', 'i', 'c', 'h', ' ', 'w', 'i', 'l', 'l', ' ', 'c', 'o', 's', 't', ' ', '$', '.']rules
- If there are numbers, they must be at the end
- Letters can be lowercase or uppercase
- At least two characters long.
- Two letter name can't have numbers.
Hint. : curly brace {} indicate the number of times the previous thing can match. The first arguement in the curly brace is the minimum and the second value is the maximum, leaving the maximum alone without specifying something means infinity eg {5,} means a minimum of 5 and maximum of inifinity
letusername="JackOfAllTrades";letuserCheck=/change/;//change this lineletresult=userCheck.test(username);console.log(result);solution
letusername="JackOfAllTrades";letuserCheck=/^[A-Za-z]{2,}\d*$/;//change this lineletresult=userCheck.test(username);console.log(result);Match whitespaces
We can match whitespace characters with \s, this will match tabs, spaces, character feed and new line characters
letsample="Whitespace is important in seperating words";letregSampleSpace=/\s/g;letresult=sample.match(regSampleSpace);console.log(result);// [ ' ', ' ', ' ', ' ', ' ' ]Match non-whitespace character
We use capital letters to match non-whitespace characters
letsample="Whitespace is important in seperating words";letregSampleSpace=/\S/g;letresult=sample.match(regSampleSpace);console.log(result);// ['W', 'h', 'i', 't', 'e', 's', 'p' 'a', 'c', 'e', 'i', 's', 'i', 'm', 'p', 'o', 'r', 't', 'a', 'n', 't', 'i', 'n', 's', 'e', 'p', 'e', 'r', 'a', 't', 'i', 'n', 'g', 'w', 'o', 'r', 'd', 's']Specify upper and lower number of matches
You can specify the lower and upper number of matches with quantity specifiers.
Quantity specifiers are used with curly brackets with the first arguement being lower and the second upper
letohStr="ohhh no";letohRegex=/Oh{3,6}no/;// This will match letter O then match h but only match if there is between 3 and 6 hletresult=ohRegex.test(ohStr);console.log(result);Specify only lower number of matches
lethaStr="Hazzzzah";lethaRegex=/z{4,}/;letresult=haRegex.test(haStr);//trueconsole.log(result);Specify the exact number of matches
We can also specify an exact number of matches
Here we use curly braces with only one arguement, no comma.
lettimStr="Timmmmber";lettimRegex=/Tim{4}ber/;letresult=timRegex.test(timStr);console.log(result);// trueCheck for all or none
We can check for possible existence of an element with a question mark.
This checks for 0 or 1 of the preceding elements, it is kind of saying the previous element is optional
letfavWord="Favorite";letfavRegex=/Favou?rite/;// We are saying it may have a u or it may not have a uletresult=favRegex.test(favWord);console.log(result);// truePositive and negative lookahead
Lookaheads are patterns that tell javascript to look ahead in your string to check for pattern further along.
This can be useful when we want to search for multiple patterns in a string.
There are positive look aheads and negative look aheads
= means positive and ! means negative lookahead
letquit="qu";letnoquit="qt";letquRegexPositive=/q(?=u)/;// this will match letter q and then look if there is a u later in the string, if there is, then it will return the qletqRegexNegative=/q(?!u)/;// this will match q and then check if there is no u later in the string and if there is none, it will match the q, if there is, then it will not match itconsole.log(quit.match(quRegexPositive));//['q']console.log(noquit.match(qRegexNegative));//['q']Reuse patters using capture groups
You can group things you are searching for in a parentheses.
letrepeatStr="regex regex";letrepeatRegex=/(\w+)\s\1/;// we are repeating (\w+) 1 times if we had another group, we could repeat that with \2// This is instead of /(\w+)\s(\w+)/console.log(repeatRegex.test(repeatStr));// trueconsole.log(repeatStr.match(repeatRegex));// ["regex regex", "regex"];// we have "regex regex" for the original match i.e (\w+)\s which was to match any number of alphabets and then a space and then we have the "regex" since the patter (\w+) in the capture group was repeated but this time without a spaceIn the example below, we use capture groups to match numbers that have been repeated only three times in a string each seperated by a space
letrepeatNum="42 42 42";letreRegex=/^(\d+)\s\1\s\1$/;letresult=reRegex.test(repeatNum);console.log(result);// returns true for any group of three numbersUse capture groups to find and replace
You can search and replace using js replace function by harnessing the power of regex.
The first input is the regex pattern and the second the string to replace.
letwrongText="The sky is silver";letsilverRegex=/silver/;wrongText.replace(silverRegex,"blue");// we can also access capture groups with dollar signs"Code Camp".replace(/(\w+)\s(w+)/,"$2 $1");// Returns camp code// $2 points to Camp and $1 points to codeRemove whitespace from start and end
lethello=" Hello, World! ";letwsRegex=/^\s+|\s+$/g;letresult=hello.replace(wsRegex,"");console.log(result);// Hello, World!