Regular Expressions Basics
Regex Literals
Create a regular expression literal and test a word.
regex-literal
A regular expression literal writes a pattern between slashes. The `test` method returns a boolean for whether the pattern appears in the text.
Regex Literals
regex_literal.js
Replay: real traced execution (multi-file project)
const word = "cat";
const pattern = /cat/;
const matched = pattern.test(word);
console.log("word=" + word);
console.log("matched=" + matched);
const word = "dog";
const pattern = /cat/;
const matched = pattern.test(word);
console.log("word=" + word);
console.log("matched=" + matched);
const word = "catalog";
const pattern = /cat/;
const matched = pattern.test(word);
console.log("word=" + word);
console.log("matched=" + matched);
word ← cat, pattern ← /cat/, matched ← true
1const word→ cat = "cat"; //@word="dog", "catalog"2const pattern→ /cat/ = /cat/;3const matched→ true = pattern/cat/.test(wordcat);45console.log("word=" + wordcat);6console.log("matched=" + matchedtrue);outputword=cat matched=true
word ← dog, pattern ← /cat/, matched ← false
1const word→ dog = "dog";2const pattern→ /cat/ = /cat/;3const matched→ false = pattern/cat/.test(worddog);45console.log("word=" + worddog);6console.log("matched=" + matchedfalse);outputword=dog matched=false
word ← catalog, pattern ← /cat/, matched ← true
1const word→ catalog = "catalog";2const pattern→ /cat/ = /cat/;3const matched→ true = pattern/cat/.test(wordcatalog);45console.log("word=" + wordcatalog);6console.log("matched=" + matchedtrue);outputword=catalog matched=true