Regular expressions JS

Username

/^[a-z0-9_-]{3,16}$/

Email

/^[A-Z0-9._%+-]+@[A-Z0-9-]+.+.[A-Z]{2,4}$/i

Phone

/^\+?(\d{1,3})?[- .]?\(?(?:\d{2,3})\)?[- .]?\d\d\d[- .]?\d\d\d\d$/

Password

/^(?=.*[A-Z].*[A-Z])(?=.*[!@#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{8,}$/

Zip-code

In Russia

/^\d{6}$/

In USA

/^\d{5}(?:[-\s]\d{4})?$/

Credit card number

/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/

Spaces

/^[ \s]+|[ \s]+$/g
let str = " hello ";
console.log(str.length); // 7
str = str.replace(re, '');
console.log(str.length); // 5

Date

/^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/

Price

/(\$[0-9,]+(\.[0-9]{2})?)/
let price = 'price $5,555.55'.match(re)[0]; '$5,555.55

URL

/[-a-zA-Z0-9@:%_\+.~#?&\/=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&\/=]*)?/gi
re.test('https://yandex.ru'); // true
re.test('yandex.ru'); // true
re.test('hello world'); // false

Twitter username

/@([A-Za-z0-9_]{1,15})/

Facebook URL

/(?:http:\/\/)?(?:www\.)?facebook\.com\/(?:(?:\w)*#!\/)?(?:pages\/)?(?:[\w\-]*\/)*([\w\-]*)/

Youtube video’s ID

/https:\/\/(?:youtu\.be\/|(?:[a-z]{2,3}\.)?youtube\.com\/watch(?:\?|#\!)v=)([\w-]{11}).*/gi

HEX colors

/\#([a-fA-F]|[0-9]){3, 6}/

Image URL

/\< *[img][^\>]*[src] *= *[\"\']{0,1}([^\"\'\ >]*)/

HTML Comments delete

/<!--(.*?)-->/

Get HTML Title

/<title>([^<>]*?)</title>/

rel=«nofollow»

$html = '<a href="https://site.com">site.com</a>,
      <a href="my-site.com">my-site.com</a>,
      <a href="https://site.com" rel="nofollow">site.com</a>';
$re = '/(<a\s*(?![^>]*\brel=)([^>]*\bhref=\"https?:\/\/[^"]+\"))/';
$result = preg_replace($re, '$1 rel="nofollow"', $html);

Searched word highlight

/\b(ipsum)\b/ig
let text = 'Lorem ipsum dolor, lorem ipsum dolor.';
text.replace(re, '<span style="background: yellow">$&</span>')

Delete repeated words

/(\w+)\s+\1/gi
"hello world world hello".replace(re, "$1") // hello world hello

Number of words

^[^\s]*$ &nbsp; // ровно одно слово
^[^\s]*\s[^\s]*$ // ровно два слова
^[^\s]*\s[^\s]* // два слова и больше
^([^\s]*\s){2}[^\s]*$ // ровно три слова
^([^\s]*\s){4, }[^\s]*$ // пять слов и больше
(Visited 36 times, 1 visits today)

Leave a comment

Your email address will not be published. Required fields are marked *