JavaScript Essentials - Regular Expressions
Using regular expressions in JavaScript
Regular expressions (regex) are patterns used to match character combinations in strings. This tutorial covers how to create and use regular expressions in JavaScript to manipulate and search text.
Key Points:
- Regular expressions provide a powerful way to perform pattern matching.
- They can be used for searching, replacing, and validating strings.
- Understanding regex can greatly enhance your text processing capabilities.
Creating Regular Expressions
In JavaScript, regular expressions can be created using the RegExp
constructor or by using forward slashes to enclose the pattern.
// Using RegExp constructor
let regex1 = new RegExp('abc');
console.log(regex1.test('abc')); // Output: true
// Using forward slashes
let regex2 = /abc/;
console.log(regex2.test('abc')); // Output: true
Common Methods
Test
The test
method tests for a match in a string. It returns true
or false
.
let regex = /hello/;
console.log(regex.test('hello world')); // Output: true
console.log(regex.test('hi there')); // Output: false
Exec
The exec
method executes a search for a match in a string. It returns an array of information or null
if no match is found.
let regex = /hello/;
let result = regex.exec('hello world');
console.log(result); // Output: ["hello", index: 0, input: "hello world", groups: undefined]
Match
The match
method retrieves the result of matching a string against a regular expression.
let str = 'hello world';
let regex = /hello/;
console.log(str.match(regex)); // Output: ["hello", index: 0, input: "hello world", groups: undefined]
Regex Patterns
Character Classes
Character classes define a set of characters to match.
let regex = /[a-z]/; // Matches any lowercase letter
console.log(regex.test('abc')); // Output: true
console.log(regex.test('123')); // Output: false
Quantifiers
Quantifiers specify how many instances of a character, group, or character class must be present for a match.
let regex = /a{2,4}/; // Matches between 2 and 4 'a' characters
console.log(regex.test('aaa')); // Output: true
console.log(regex.test('a')); // Output: false
Anchors
Anchors are used to match positions within a string.
let regex = /^hello/; // Matches 'hello' at the start of a string
console.log(regex.test('hello world')); // Output: true
console.log(regex.test('world hello')); // Output: false
Summary
In this tutorial, you learned how to use regular expressions in JavaScript. Mastering regex allows you to perform complex pattern matching and text manipulation tasks efficiently.