A regular expression is a syntax that represents a search pattern in a string of characters.
In JavaScript, regular expressions are used to perform string matching and manipulation operations. For example,
- Searching and replacing parts of a string
- Validating data formats (for example, emails, phone numbers)
- Splitting strings based on specific patterns
Regular expressions may seem complicated at first due to their compact syntax, but they offer great flexibility and power once mastered.
Creating Regular Expressions in JavaScript
In JavaScript, regular expressions can be defined in two ways: using a regular expression literal or the RegExp
constructor.
Regular Expression Literal
The syntax for creating a regular expression using a literal is:
const regex = /expression/flags;
The flags
option is optional and is used to modify the behavior of the regular expression (for example, i
for case-insensitive matching).
For example,
const regex = /abc/;
In this case,
/abc/
is a regular expression that matches the string “abc”.
RegExp Constructor
The syntax for creating a regular expression using the RegExp
constructor is:
const regex = new RegExp(expression, 'flags');
For example, this creates a regular expression equivalent to /abc/
const regex = new RegExp('abc');
The constructor is useful when the pattern is defined dynamically (for example, from a variable)
Methods for Working with Regular Expressions
JavaScript provides several useful methods for working with regular expressions through the RegExp
property and string methods (String
).
RegExp.test()
The test()
method of RegExp
is used to check if a regular expression matches a string.
const regex = /hola/;
console.log(regex.test('hola mundo')); // true
console.log(regex.test('adiós mundo')); // false
RegExp.exec()
The exec()
method of RegExp
searches for a match in a string and returns an array with the match or null
if there is no match.
const regex = /(\d+)/;
const resultado = regex.exec('Tengo 2 manzanas');
console.log(resultado); // ["2", "2"]
String.match()
The match()
method of String
is used to get the matches of a regular expression in a string. It returns an array with the matches or null
if there is no match.
const texto = 'La fecha es 2024-08-14';
const regex = /\d{4}-\d{2}-\d{2}/;
const resultado = texto.match(regex);
console.log(resultado); // ["2024-08-14"]
String.replace()
The replace()
method of String
is used to replace parts of a string that match a regular expression.
const texto = 'Mi número de teléfono es 123-456-7890';
const regex = /\d{3}-\d{3}-\d{4}/;
const nuevoTexto = texto.replace(regex, 'XXX-XXX-XXXX');
console.log(nuevoTexto); // "Mi número de teléfono es XXX-XXX-XXXX"
String.split()
The split()
method of String
is used to split a string into an array using a regular expression as a delimiter.
const texto = 'uno,dos,tres';
const regex = /,/;
const resultado = texto.split(regex);
console.log(resultado); // ["uno", "dos", "tres"]