Home > Web Front-end > JS Tutorial > js/ts - regular expression

js/ts - regular expression

Patricia Arquette
Release: 2024-09-21 08:30:39
Original
257 people have browsed it

js / ts - expressão regular

Of course! Here is an example of how to use regular expressions (regex) in TypeScript:

Example: Validate an email address

// Função para validar e-mail usando regex
function validarEmail(email: string): boolean {
    const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    return regex.test(email);
}

// Testando a função
const email1 = "teste@example.com";
const email2 = "invalid-email@.com";

console.log(`${email1} é válido? ${validarEmail(email1)}`); // Saída: teste@example.com é válido? true
console.log(`${email2} é válido? ${validarEmail(email2)}`); // Saída: invalid-email@.com é válido? false
Copy after login

Regex Description:

  • ^: Start of string.
  • [a-zA-Z0-9._%+-]+: One or more alphanumeric characters, including periods, underscores, percentages, plus and minus signs.
  • @: An "@" character.
  • [a-zA-Z0-9.-]+: One or more alphanumeric characters or periods and hyphens.
  • .: A literal period character.
  • [a-zA-Z]{2,}: Two or more letters (for the top-level domain such as .com, .org, etc.).
  • $: End of string.

This example shows how you can use regex to validate an email format in TypeScript. If you need more examples or explanations, feel free to ask!

by ChatGPT

The above is the detailed content of js/ts - regular expression. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template