JavaScript Regular Expressions
Regular expressions (RegEx) are patterns used to match character combinations in strings. They can be used for tasks like searching, replacing, and validating strings. Here’s a guide to using regular expressions in JavaScript:
Basic Syntax
Regular expressions in JavaScript can be created using either a literal notation or the `RegExp` constructor. The syntax for a regular expression literal is:
let regex = /pattern/flags;
For example:
let regex = /abc/i; // Matches 'abc' case-insensitively
Flags
Flags modify the behavior of the regular expression. Common flags include:
- g - Global match (find all matches)
- i - Case-insensitive match
- m - Multi-line match
- s - Dotall mode (matches newline characters)
- u - Unicode; treat pattern as a sequence of Unicode code points
- y - Sticky; matches only from the last index position
Methods
JavaScript strings and regular expressions have several useful methods:
- test() - Tests if a pattern exists in a string
let regex = /test/;
console.log(regex.test('This is a test')); // true
let regex = /test/;
console.log(regex.exec('This is a test')); // ['test', index: 15, input: 'This is a test', groups: undefined]
let str = 'This is a test';
console.log(str.match(/test/)); // ['test']
let str = 'This is a test';
console.log(str.replace(/test/, 'example')); // 'This is a example'
let str = 'one,two,three';
console.log(str.split(/,/)); // ['one', 'two', 'three']