Корисні regex-патерни для реальних задач:
1class="hl-comment">// Email
2/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
3
4class="hl-comment">// URL
5/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b/
6
7class="hl-comment">// Телефон (гнучкий)
8/^[+]?[(]?[0-9]{3}[)]?[-\s.]?[0-9]{3}[-\s.]?[0-9]{4,6}$/
9
10class="hl-comment">// Дата YYYY-MM-DD
11/^(19|20)\d{2}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/
12
13class="hl-comment">// IP-адреса
14/^(25[0-5]|2[0-4]\d|[01]?\d\d?)(\.(25[0-5]|2[0-4]\d|[01]?\d\d?)){3}$/
15
16class="hl-comment">// Slug (для URL)
17/^[a-z0-9]+(?:-[a-z0-9]+)*$/
18
19class="hl-comment">// Markdown посилання
20/\[([^\]]+)\]\(([^)]+)\)/gconst toKebab = s => s.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
const toCamel = s => s.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
console.log(toKebab('backgroundColor'));
console.log(toKebab('myVariableName'));
console.log(toCamel('border-top-color'));
function maskSensitive(text) {
return text
.replace(/[\w.+-]+@[\w.-]+\.[a-z]{2,}/gi, '[EMAIL]')
.replace(/\d{4,}/g, '[NUMBER]');
}
console.log(maskSensitive("Зв\'яжіться з john@example.com або +380991234567"));
function template(str, data) {
return str.replace(/\{\{(\w+)\}\}/g, (match, key) => data[key] !== undefined ? data[key] : match);
}
console.log(template('Привіт, {{name}}! Тобі {{age}} років.', {name:'Оля', age:25}));
console.log(template('{{greeting}}, {{name}}!', {name:'Іван'}));