¡GoConqr estrena diseño! Cuéntanos qué te parece.

Apuntes

javscript regular expression

Artisan php Javscript Advance Inglés 2 páginas

Contenido del apunte (2)

Página 1

Let's start with some basics:

Creating a Regular Expression: In JavaScript, you can create a regular expression using slashes / like this:

javascriptCopy code

/pattern/

For example, if you want to find the word "apple" in a text, you can create a regex like this:

javascriptCopy code

/apple/

Matching Text: You can use the .test() method to check if a regex pattern matches a string. It returns true if there's a match and false if there isn't.

javascriptCopy code

var text = "I have an apple."; var pattern = /apple/; var result = pattern.test(text); console.log(result); // This will print true

Character Classes: You can use square brackets [ ] to match any one character from a set. For example, [aeiou] matches any vowel.

javascriptCopy code

var text = "The cat and the hat."; var pattern = /[aeiou]/g; // 'g' stands for global, so it matches all vowels var vowels = text.match(pattern); console.log(vowels); // This will print an array of vowels: ['e', 'a', 'e', 'a']

Quantifiers: You can use quantifiers to specify how many times a character or group of characters should appear. For example:

* matches zero or more times.

+ matches one or more times.

? matches zero or one time.

{n} matches exactly n times.

{n,} matches at least n times.

{n, m} matches between n and m times.

javascriptCopy code

var text = "Mississippi"; var pattern = /s+/g; // Matches one or more 's' characters var matches = text.match(pattern); console.log(matches); // This will print ["ss", "ss"]

Special Characters: Some characters have special meanings in regex and need to be escaped with a backslash \ if you want to match them literally. For example, to match a dot . or a question mark ?, you would write \., \?.

Here's a simple example that puts some of these concepts together:

javascriptCopy code

var text = "I have 3 apples and 2 bananas."; var pattern = /\d+/g; // Matches one or more digits var numbers = text.match(pattern); console.log(numbers); // This will print an array of numbers: ['3', '2']

Remember, regular expressions can get quite complex, but these basics should help you get started. Like learning to build with blocks, it takes practice, so keep experimenting and trying different patterns!

Página 2

Información

Descripción
Advance Javscript Apunte sobre javscript regular expression, creado por Artisan php el 01/10/2023.
Creado por
Artisan php · oct 2023
Actualizado
1 oct 2023
Visitas
0
Valoración

Escríbenos

¿Sobre qué es tu mensaje?

¿Qué te parece el nuevo diseño?

¿Te gusta?