Skip to content

Commit 0193035

Browse files
#16 - javascript
1 parent 311dd05 commit 0193035

File tree

1 file changed

+196
-0
lines changed

1 file changed

+196
-0
lines changed
Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
// #16 EXPRSIONES REGULARES
2+
// bibliography reference
3+
// Professional JavaScript for web developers by Matt Frisbie [Frisbie, Matt] (z-lib.org)
4+
5+
/* EJERCICIO:
6+
* Utilizando tu lenguaje, explora el concepto de expresiones regulares,
7+
* creando una que sea capaz de encontrar y extraer todos los números
8+
* de un texto.
9+
*
10+
* DIFICULTAD EXTRA (opcional):
11+
* Crea 3 expresiones regulares (a tu criterio) capaces de:
12+
* - Validar un email.
13+
* - Validar un número de teléfono.
14+
* - Validar una url.*/
15+
16+
// short for console.log()
17+
let log = console.log;
18+
19+
window.addEventListener('load', ()=>{
20+
const body = document.querySelector('body');
21+
const title = document.createElement('h1');
22+
23+
body.style.setProperty('background', '#000');
24+
body.style.setProperty('text-align', 'center');
25+
26+
title.textContent = 'Retosparaprogramadores #16.';
27+
title.style.setProperty('font-size', '3.5vmax');
28+
title.style.setProperty('color', '#fff');
29+
title.style.setProperty('line-height', '100vh');
30+
31+
body.appendChild(title);
32+
33+
setTimeout(()=>{
34+
alert('Retosparaprogramadores #16. Please open the Browser Developer Tools.');
35+
}, 2000);
36+
log( 'Retosparaprogramadores #16');
37+
});
38+
39+
/*
40+
Some Flags (also known as a modifiers)
41+
➤➤
42+
g—Indicates global mode, meaning the pattern will be applied to all of the string instead of
43+
stopping after the first match is found.
44+
➤➤
45+
i—Indicates case-insensitive mode, meaning the case of the pattern and the string are
46+
ignored when determining matches.
47+
➤➤
48+
m—Indicates multiline mode, meaning the pattern will continue looking for matches after
49+
reaching the end of one line of text.
50+
➤➤
51+
y—Indicates sticky mode, meaning the pattern will only look at the string contents
52+
beginning at lastIndex.
53+
➤➤
54+
u—Indicates Unicode mode is enabled.
55+
*/
56+
57+
58+
/*
59+
As with regular expressions in other languages, all metacharacters must be escaped when used as part
60+
of the pattern. The metacharacters are as follows:
61+
( [ { \ ^ $ | ) ] } ? * + .
62+
*/
63+
64+
/*
65+
Each instance of RegExp has the following properties that allow you to get information about
66+
the pattern:
67+
➤➤
68+
global—A Boolean
69+
value indicating whether the g flag has been set.
70+
➤➤
71+
ignoreCase—A Boolean value indicating whether the i flag has been set.
72+
➤➤
73+
unicode—A Boolean value indicating whether the u flag has been set.
74+
➤➤
75+
sticky—A Boolean value indicating whether the y flag has been set.
76+
➤➤
77+
lastIndex—An integer indicating the character position where the next match will be
78+
attempted in the source string. This value always begins as 0.
79+
➤➤
80+
multiline—A Boolean value indicating whether the m flag has been set.
81+
➤➤
82+
source—The string source of the regular expression. This is always returned as if specified
83+
in literal form (without opening and closing slashes) rather than a string pattern as passed
84+
into the constructor.
85+
➤➤
86+
flags—The string flags of the regular expression. This is always returned as if specified in
87+
literal form (without opening and closing slashes) rather than a string pattern as passed into
88+
the constructor.
89+
*/
90+
91+
92+
// Define a pattern and flags
93+
const pattern0 = 'abc';
94+
const flags = 'gi'; // Global and case-insensitive
95+
96+
// Create a regular expression using the RegExp constructor
97+
const regex = new RegExp(pattern0, flags);
98+
99+
log(regex); // /abc/gi
100+
101+
let text = "time: 08:07:06";
102+
let pattern1 = /(time(:)?)? ?([01][0-9]|2[0-3])([:/-])([0-5][0-9])\4([0-5][0-9])/;
103+
104+
/*
105+
**Explanation of the regular expression:**
106+
- **(time(:)?)**: Optionally matches the word "time" followed by an optional colon (:).
107+
- **?**: Matches an optional space.
108+
- **([01][0-9]|2[0-3])**: Matches the hour, allowing values from 00 to 23.
109+
- **[01][0-9]**: Matches hours from 00 to 19.
110+
- **|**: "Or" operator.
111+
- **2[0-3]**: Matches hours from 20 to 23.
112+
- **([:/-])**: Matches one of the characters :, /, or - and captures it for later use.
113+
- **([0-5][0-9])**: Matches the minutes (00 to 59).
114+
- **\4**: References the fourth captured group, which is the separator (it must be the same as used between the hour and the minutes).
115+
- **([0-5][0-9])**: Matches the seconds (00 to 59).
116+
*/
117+
118+
let matches1 = pattern1.exec(text);
119+
120+
if(matches1){
121+
log(matches1.index); // 0
122+
log(matches1.input); // time: 08:07:06
123+
log(matches1[0]); // time: 08:07:06
124+
log(matches1[1]); // time:
125+
log(matches1[2]); // :
126+
}
127+
128+
let pattern = /[0-9]/g;
129+
let matches = pattern.exec(text);
130+
if(matches) log(matches) // ['0', index: 6, input: 'time: 08:07:06', groups: undefined]
131+
132+
let matches3 = text.match(pattern);
133+
if(matches3) log(matches3) // ['0', '8', '0', '7', '0', '6']
134+
135+
//Note: that match() return all concidence when using global flat g
136+
137+
if(matches3){
138+
log(matches3.index); // undefined
139+
log(matches3.input); // undefined
140+
log(matches3[0]); // 0
141+
log(matches3[1]); // 8
142+
log(matches3[2]); // 0
143+
}
144+
145+
let pattern2 = /\d/g
146+
let matches2 = pattern2.exec(text);
147+
if(matches2) log(matches2) // ['0', index: 6, input: 'time: 08:07:06', groups: undefined]
148+
149+
let matches4 = text.match(pattern2);
150+
if(matches4) log(matches4) // ['0', '8', '0', '7', '0', '6']
151+
152+
/*
153+
exec: Returns the first match and can be used in a loop to find all matches.
154+
155+
match: Returns an array with all matches in a more direct and straightforward way.
156+
*/
157+
158+
//Extra Dificulty Exercise:
159+
160+
const validateTlf = (num)=>{
161+
if (!/^\d{11}$/.test(num)) {
162+
console.log("Invalid telephone number. Must be a numeric value and have 11 digits.");
163+
return false;
164+
}
165+
return true;
166+
}
167+
168+
const ValidateEmail = (email)=>{
169+
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
170+
if(!emailRegex.test(email)){
171+
console.log("Invalid emnail adress");
172+
return false;
173+
}
174+
return true;
175+
}
176+
177+
const validateURL = (url)=>{
178+
const urlRegex = /^(https?:\/\/)?([a-zA-Z0-9.-]+)(:[0-9]{1,5})?(\/[^\s]*)?$/;
179+
if(!urlRegex.test(url) || (!url.startsWith('http://') && !url.startsWith('https://'))){
180+
console.log("Invalid URL");
181+
return false;
182+
}
183+
return true;
184+
}
185+
186+
let num1 = 1562737848, num2 = 34587452387, email1 = '[email protected]', email2 = '[email protected]', url1 = 'http://palnetaneurodiverso.org', url2 = 'https://moebius.org', url3 = 'something.com', url4 = 'gato';
187+
188+
log(validateTlf(num1)); // Invalid telephone number. Must be a numeric value and have 11 digits. false
189+
log(`Is a valid tlf: ${validateTlf(num2)}`) // Is a valid tlf: true
190+
log(`Is a valid tlf: ${ValidateEmail(email1)}`); // Is a valid tlf: true
191+
log(`Is a valid email: ${ValidateEmail(email2)}`); // Is a valid email: true
192+
log(`Is a valid URL: ${validateURL(url1)}`); // Is a valid URL: true
193+
log(`Is a valid URL: ${validateURL(url2)}`); // Is a valid URL: true
194+
log(`Is a valid URL: ${validateURL(url3)}`); // Invalid URL Is a valid URL: false
195+
log(`Is a valid URL: ${validateURL(url4)}`); // Invalid URL Is a valid URL: false
196+

0 commit comments

Comments
 (0)