Regular expressions, or regular expressions (abbreviated as regex or regexp), are a powerful tool in JavaScript (and many other programming languages) that allow you to perform advanced search and manipulation of text strings using patterns. In essence, regular expressions define a search pattern that can be used to find matches in text, replace text, validate data, and much more.
índice
Togglejavascript
const regex = /pattern/;
Alternatively, you can use the RegExp constructor:
Example of use with modifiers:
const regex = /text/gi;
Example of a pattern that matches a simple telephone number:
const regex = /{3}-{3}-{4}/;
const regex = /abc/;
console.log(regex.test(“abcde”)); // true
const regex = /(/(+)/;
const result = regex.exec(“There are 123 apples”);
console.log(result[0]); // “123”
const text = “The code is 123 and the other code is 456.”;
const matches = text.match(/\d+/g);
console.log(matches); // [“123”, “456”]
const text = “1, 2, 3, 4, 5”;
const newText = text.replace(/\d+/g, ‘number’);
console.log(newText); // “number, number, number, number, number, number, number”.
To validate a basic email, you can use the following regular expression:
const emailRegex = /^[a-zA-Z0-9 ._%+-]+@[a-zA-Z0-9 .-]+.[a-zA-Z]{2,}$/;
const isValid = emailRegex.test(“ejemplo@dominio.com”);
console.log(isValid); // true
Regular expressions in JavaScript are a powerful and flexible tool for string handling. Although they may seem complicated at first, they are extremely useful for validating, searching and manipulating text in multiple contexts.