Method of use
1.text()
let myString = "Hello, World!";
let myRegex = /Hello/;
myString.test(myRegex);
Copy the code
Using | matching multiple characters
let petString = "James has a pet cat.";
let petRegex = /dog|cat|bird|fish/;
let result = petRegex.test(petString)
Copy the code
2.match()
let extractStr = "Extract the word 'coding' from this string.";
let codingRegex = /coding/;
let result = extractStr.match(codingRegex)
Copy the code
let twinkleStar = "Twinkle, twinkle, little star";
let starRegex = /Twinkle/gi;
let result = twinkleStar.match(starRegex)
Copy the code
Add g to the end of the regular expression to indicate full match and I to indicate ignoring case.
Regular expression symbol
Matches any character
let exampleStr = "Let's have fun with regular expressions!";
let unRegex = /.un/; // Change this line
let result = unRegex.test(exampleStr);
Copy the code
[] Matches one of the characters
let quoteSample = "Beware of bugs in the above code; I have only proved it correct, not tried it.";
let vowelRegex = /[aeiou]/gi;
let result = qutoeSample.match(vowelRegex);
Copy the code
let quoteSample = "The quick brown fox jumps over the lazy dog.";
let alphabetRegex = /[a-e]/gi;
let result = quoteSample.match(alphabetRegex);
Copy the code
^ Take the character following the reverse mismatch
let quoteSample = "3 blind mice.";
let myRegex = /[^aeiou^0-9]/gi;
let result = quoteSample.match(myRegex);
Copy the code
Start with ^ match
let firstString = "Ricky is first and can be found.";
let firstRegex = /^Ricky/;
firstRegex.test(firstString); True
let notFirst = "You can't find Ricky now.";
firstRegex.test(notFirst); False
Copy the code
Use $to match the end
let theEnding = "This is a never ending story";
let storyRegex = /story$/;
storyRegex.test(theEnding); True
let noEnding = "Sometimes a story will have to end";
storyRegex.test(noEnding); False
Copy the code
+ Matches one or more characters
let difficultSpelling = "Mississippi";
let myRegex = /s+/gi;
let result = difficultSpelling.match(myRegex);
Copy the code
* Matches zero or more characters
let chewieQuote = "Aaaaaaaaaaaaaaaarrrgh!";
let chewieRegex = /Aa*/;
let result = chewieQuote.match(chewieRegex);
Copy the code
\w corresponds to matching \ a-za-z0-9_ \d as opposed to matching \0-9 \d, which matches non-digits \s matching Spaces {} matching A certain number of characters
let ohStr = "Ohhh no";
let ohRegex = / Oh no / {3, 6};
let result = ohRegex.test(ohStr);
Copy the code
Advance matching (to be completed)