Lesson 62 - Basic Regular Expression Patterns in JavaScript
Regular expressions (RegEx) are patterns used to match character combinations in strings. JavaScript provides the RegExp
object for defining and working with these patterns.
Creating a Regular Expression
There are two ways to create a RegEx in JavaScript:
- Using RegExp constructor:
new RegExp("pattern")
- Using regex literal:
/pattern/
Example:
let regex1 = new RegExp("hello");
let regex2 = /hello/;
Basic RegEx Patterns
1. Matching Exact Text
let text = "Hello world";
let pattern = /world/;
console.log(pattern.test(text)); // true
2. Case-Insensitive Matching
Use the i
flag to ignore case:
let pattern = /hello/i;
console.log(pattern.test("HELLO")); // true
3. Matching Digits and Word Characters
\d
? Matches any digit (0-9)\w
? Matches any word character (letters, digits, underscore)
Example:
let text = "User123";
console.log(/\d/.test(text)); // true
console.log(/\w/.test(text)); // true
4. Matching Whitespace Characters
\s
? Matches any whitespace (space, tab, newline)\S
? Matches any non-whitespace character
Example:
let text = "Hello World";
console.log(/\s/.test(text)); // true (contains space)
5. Matching Any Character (Except Newline)
The dot .
matches any single character except newline:
let pattern = /h.t/;
console.log(pattern.test("hat")); // true
console.log(pattern.test("hit")); // true
console.log(pattern.test("hot")); // true
6. Matching at the Beginning and End
^
? Matches the beginning of a string$
? Matches the end of a string
Example:
console.log(/^Hello/.test("Hello world")); // true
console.log(/world$/.test("Hello world")); // true
Summary
- Regular expressions are used for pattern matching in JavaScript.
- Common patterns include
\d
,\w
,\s
,.
,^
, and$
. - Flags like
i
make the matching case-insensitive.
Try Your Hand
- Write a RegEx to match any string that starts with "Java".
- Write a RegEx to check if a string contains at least one digit.