JavaScript Regular Expressions freecodecamp
Regular expressions, often shortened to “regex” or “regexp”, are patterns that help programmers match, search, and replace text. Regular expressions are very powerful, but can be hard to read because they use special characters to make more complex, flexible matches.
In this course, you’ll learn how to use special characters, capture groups, positive and negative lookaheads, and other techniques to match any text you want.
Using the Test Method
let myString = “Hello, World!”;
let myRegex = /Hello/;
let result = myRegex.test(myString); // Change this line
Match Literal Strings
let waldoIsHiding = “Somewhere Waldo is hiding in this text.”;
let waldoRegex = /Waldo/; // Change this line
let result = waldoRegex.test(waldoIsHiding);
console.log(result);
Match a Literal String with Different Possibilities
let petString = “James has a pet cat.”;
// 用or的符號 | 來區別要找的東西
let petRegex = /dog|cat|bird|fish/; // Change this line
let result = petRegex.test(petString);
Ignore Case While Matching
let myString = “freeCodeCamp”;
let fccRegex = /freeCodeCamp/i; // Change this line 用這個方法可以忽略大小寫文字
let result = fccRegex.test(myString);
Extract Matches
So far, you have only been checking if a pattern exists or not within a string. You can also extract the actual matches you found with the .match()
method.
To use the .match()
method, apply the method on a string and pass in the regex inside the parentheses.
let extractStr = “Extract the word ‘coding’ from this string.”;
let codingRegex = /coding/; // Change this line
let result = extractStr.match(codingRegex); // Change this line
console.log(result);
[ ‘coding’,
index: 18,
input: ‘Extract the word \’coding\’ from this string.’,
groups: undefined ]
Find More Than the First Match
Match Anything with Wildcard Period
Match Single Character with Multiple Possibilities
Not PassedMatch Letters of the Alphabet
Not PassedMatch Numbers and Letters of the Alphabet
Not PassedMatch Single Characters Not Specified
留言