Java Script regular expressions

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.

Features of Regular Expressions in JavaScript

Basic syntax:

  1. A regular expression is defined between two slashes /:

javascript

const regex = /pattern/;

Alternatively, you can use the RegExp constructor:

Modifiers

  • Modifiers alter the way the pattern searches the text:
    • g (global): Finds all matches, not just the first one.
    • i (ignore case): Ignores the differences between upper and lower case.
    • m (multiline): Allows ^ and $ to match at the beginning and end of each line, not only at the beginning and end of the whole text.

Example of use with modifiers:

const regex = /text/gi;

Special Characteristics

  • Some characters have special meanings in regular expressions:
    • Matches any character except a new line.
    • \d: Match any digit, equivalent to [0-9].
    • \w: Matches any word character (letters, numbers and underscore).
    • \s: Matches any blank space (space, tab, new line).
    • *: Matches 0 or more repetitions of the previous pattern.
    • +: Coincides with 1 or more repetitions of the previous pattern.
    • {n,m}: Matches at least n and at most m repetitions of the previous pattern.

Example of a pattern that matches a simple telephone number:

const regex = /{3}-{3}-{4}/;

Common Methods

  • test: Checks if a pattern exists in the text. Returns true or false.

const regex = /abc/;

console.log(regex.test(“abcde”)); // true

  • exec: Searches for a match and returns an array with details of the match, or null if nothing is found.

const regex = /(/(+)/;

const result = regex.exec(“There are 123 apples”);

console.log(result[0]); // “123”

  • match: Searches for matches and returns an array with all of them.

const text = “The code is 123 and the other code is 456.”;

const matches = text.match(/\d+/g);

console.log(matches); // [“123”, “456”]

  • replace: Replaces matches in text with a new value.

const text = “1, 2, 3, 4, 5”;

const newText = text.replace(/\d+/g, ‘number’);

console.log(newText); // “number, number, number, number, number, number, number”.

  • Practical Example: Validation of an Email.

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

Conclusion.

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.