← Tutorials ☕ Java 🧩 DSA 🌿 Spring Boot 🚀 DevOps 🗂 MySQL 🏗 System Design ❓ FAQ 🌐 HTML 🔇 JavaScript ⚛ ReactJS 🌻 NodeJS 🐍 Python 🍏 MongoDB 📋 Cheatsheet
Tutorials › Cheatsheet

HTML5 Cheatsheet

Quick reference for HTML elements, attributes & structure

Document Structure
Boilerplate
<!DOCTYPE html> // HTML5 doctype
<html lang="en"> // root element
<head> ... </head> // metadata block
<body> ... </body> // visible content
<meta charset="UTF-8"> // character encoding
<meta name="viewport" // responsive meta
content="width=device-width,initial-scale=1">
<title>Page Title</title>
<link rel="stylesheet" href="style.css">
<script src="app.js" defer></script>
Semantic Elements
<header>Page or section header
<nav>Navigation links
<main>Main content (one per page)
<section>Thematic grouping
<article>Self-contained content
<aside>Sidebar / related content
<footer>Page or section footer
<figure>Media + caption
<figcaption>Caption for <figure>
<time>Date/time with datetime attr
Text Elements
<h1>–<h6>Headings (1=most important)
<p>Paragraph
<strong>Bold / important
<em>Italic / emphasis
<br>Line break
<hr>Horizontal rule
<span>Inline container
<div>Block container
<blockquote>Block quote
<code>Inline code
<pre>Preformatted text
Links, Images & Media
<a href="url" target="_blank">Link</a>
<img src="img.png" alt="desc" loading="lazy">
<picture>
<source media="(max-width:600px)" srcset="sm.jpg">
<img src="lg.jpg" alt="...">
</picture>
<video controls autoplay muted loop>
<source src="vid.mp4" type="video/mp4">
</video>
<audio controls src="audio.mp3"></audio>
<iframe src="url" title="..."></iframe>
Forms
<form action="/api" method="POST">
<input type="text" name="u" required>
<input type="email" placeholder="Email">
<input type="password" minlength="8">
<input type="number" min="0" max="100">
<input type="checkbox" checked>
<input type="radio" name="g" value="m">
<select name="city">
<option value="del">Delhi</option>
</select>
<textarea rows="4"></textarea>
<button type="submit">Submit</button>
</form>
Lists & Tables
<ul><li>Item</li></ul> // unordered
<ol><li>Item</li></ol> // ordered
<dl><dt>Term</dt><dd>Def</dd></dl>
<table>
<thead><tr><th>Col</th></tr></thead>
<tbody><tr><td>Data</td></tr></tbody>
<tfoot><tr><td colspan="2">...</td></tr></tfoot>
</table>

CSS3 Cheatsheet

Quick reference for selectors, properties, Flexbox & Grid

Selectors
*All elements
divElement type
.classClass selector
#idID selector
div pDescendant
div > pDirect child
div + pAdjacent sibling
div ~ pGeneral siblings
[attr="val"]Attribute selector
:hoverPseudo-class
::beforePseudo-element
:nth-child(2n+1)Odd children
:not(.cls)Negation
:is(h1,h2,h3)Matches any
Box Model
width / heightContent size
paddingInner spacing
borderBorder around padding
marginOuter spacing
box-sizing: border-boxInclude padding+border in size
overflow: hidden|scroll|autoOverflow behaviour
display: block|inline|flex|grid|noneLayout type
visibility: hiddenHide but keep space
opacity: 0–1Transparency
Flexbox
display: flexEnable flex on container
flex-directionrow | column | row-reverse
flex-wrapnowrap | wrap
justify-contentflex-start|center|space-between
align-itemsstretch|center|flex-start|end
align-contentMulti-line cross-axis
gapSpace between items
flex: 1Grow to fill (on item)
flex-shrink: 0Don't shrink (on item)
align-selfOverride align-items per item
orderItem order (default 0)
Grid
display: gridEnable grid
grid-template-columnsrepeat(3, 1fr)
grid-template-rowsauto 100px auto
gaprow-gap / column-gap
grid-column1 / 3 (span 2 cols)
grid-row1 / span 2
place-itemsShorthand for align+justify
minmax(200px, 1fr)Responsive column size
auto-fill / auto-fitResponsive without media queries
Positioning
position: staticDefault (normal flow)
position: relativeOffset from normal position
position: absoluteRelative to nearest positioned ancestor
position: fixedRelative to viewport
position: stickySticks at threshold while scrolling
top / right / bottom / leftOffset values
z-indexStacking order
Transitions & Animations
transition: all 0.3s ease;
transition: color 0.2s, transform 0.3s;
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
animation: fadeIn 0.4s ease forwards;
animation-delay: 0.2s;
animation-iteration-count: infinite;

JavaScript (ES6+) Cheatsheet

Quick reference for modern JavaScript syntax & patterns

Variables & Types
const x = 10; // block-scoped, immutable ref
let y = 'hello'; // block-scoped, mutable
typeof x // 'number'
typeof null // 'object' (quirk!)
x === y // strict equality (use always)
x ?? 'default' // nullish coalescing
obj?.prop?.nested // optional chaining
Destructuring
const [a, b, ...rest] = [1,2,3,4];
const { name, age = 18 } = user;
const { name: n } = user; // rename
const { a: { b } } = obj; // nested
function fn({ name, age }) {} // param destruct
Arrow Functions
const add = (a, b) => a + b;
const greet = name => `Hello ${name}`;
const fn = () => ({ // return object
key: 'value'
});
const fn = async () => { // async arrow
const data = await fetchData();
return data;
};
Array Methods
.map(fn)Transform each element → new array
.filter(fn)Keep elements where fn returns true
.reduce(fn, init)Reduce to single value
.find(fn)First matching element
.findIndex(fn)Index of first match
.some(fn)True if any match
.every(fn)True if all match
.includes(val)Contains value
.flat(depth)Flatten nested arrays
.flatMap(fn)Map + flat(1)
[...a, ...b]Spread / merge arrays
Promises & Async
const p = new Promise((res, rej) => {
setTimeout(() => res('done'), 1000);
});
p.then(v => console.log(v))
.catch(e => console.error(e))
.finally(() => {});
const [a, b] = await Promise.all([p1, p2]);
const first = await Promise.race([p1, p2]);
const results = await Promise.allSettled([p1,p2]);
Object Utilities
Object.keys(obj) // ['a','b']
Object.values(obj) // [1,2]
Object.entries(obj) // [['a',1],['b',2]]
Object.assign({}, a, b) // shallow merge
const copy = { ...obj, x: 9 } // spread merge
Object.freeze(obj) // immutable object
Object.fromEntries(entries) // entries→object

Python Cheatsheet

Quick reference for Python syntax, data structures & common patterns

Data Types & Variables
x = 10 # int
y = 3.14 # float
s = "hello" # str
b = True # bool
n = None # NoneType
type(x) # <class 'int'>
isinstance(x, int) # True
a, b = 1, 2 # tuple unpacking
a, *b = [1,2,3] # a=1, b=[2,3]
Strings
f"Hello {name}" # f-string
f"{price:.2f}" # format 2 decimals
s.upper() / s.lower()
s.strip() / s.lstrip() / s.rstrip()
s.split(',') # list of substrings
','.join(['a','b']) # 'a,b'
s.replace('a','b')
s.startswith('h') / s.endswith('o')
s[1:4] / s[::-1] # slicing / reverse
len(s) # length
List / Dict / Set
lst = [1, 2, 3]
lst.append(4) / lst.pop() / lst.remove(2)
lst.sort() / sorted(lst, reverse=True)
[x*2 for x in lst if x>1] # comprehension
d = {'a': 1, 'b': 2}
d.get('c', 0) # safe get with default
d.items() / d.keys() / d.values()
{k:v for k,v in d.items() if v>1}
s = {1, 2, 3} # set — unique values
s.add(4) / s.discard(1)
s1 & s2 / s1 | s2 / s1 - s2 # intersect/union/diff
Functions & Lambdas
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
def fn(*args, **kwargs): ...
greet(name="Aftab", greeting="Hi")
square = lambda x: x ** 2
sorted(users, key=lambda u: u['age'])
def decorator(fn):
def wrapper(*args, **kwargs):
print("before")
return fn(*args, **kwargs)
return wrapper
Error Handling
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
except (TypeError, ValueError):
pass
else:
print("no error")
finally:
print("always runs")
raise ValueError("message")
Classes
class Animal:
def __init__(self, name):
self.name = name
def speak(self): return "..."
@classmethod
def create(cls, name): return cls(name)
@staticmethod
def info(): return "I am Animal"
class Dog(Animal):
def speak(self): return "Woof"

Java Cheatsheet

Quick reference for Java syntax, collections & streams

Data Types
int / long32/64-bit integer
double / float64/32-bit decimal
booleantrue / false
charSingle character (16-bit)
StringImmutable character sequence
varLocal type inference (Java 10+)
IntegerBoxed int (used in collections)
Collections
List<String> list = new ArrayList<>();
list.add("a"); list.get(0); list.size();
List.of("a","b","c"); // immutable list
Map<String,Integer> map = new HashMap<>();
map.put("key", 1); map.get("key");
map.getOrDefault("key", 0);
map.forEach((k,v) -> System.out.println(k+v));
Set<String> set = new HashSet<>();
set.add("a"); set.contains("a");
Streams API
list.stream()
.filter(s -> s.length() > 3)
.map(String::toUpperCase)
.sorted()
.distinct()
.limit(5)
.collect(Collectors.toList());
list.stream().mapToInt(Integer::parseInt).sum();
list.stream().anyMatch(s -> s.startsWith("A"));
list.stream().findFirst().orElse("default");
Optional
Optional<String> opt = Optional.of("hello");
Optional.empty(); Optional.ofNullable(val);
opt.isPresent(); opt.get();
opt.orElse("default");
opt.orElseGet(() -> compute());
opt.orElseThrow(() -> new RuntimeException());
opt.map(String::toUpperCase);
opt.filter(s -> s.length() > 3);
opt.ifPresent(System.out::println);
String Methods
.length()Character count
.charAt(i)Char at index
.substring(2,5)Substring [2..4]
.contains("sub")Contains substring
.startsWith("pre")Starts with
.split(",")Split to String[]
.trim()Remove whitespace
.toLowerCase()Lowercase
.replace("a","b")Replace occurrences
.formatted("%s %d",s,n)Java 15+ formatting
String.join(",",list)Join list to string
Exception Handling
try {
int r = 10 / 0;
} catch (ArithmeticException e) {
e.getMessage();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
// always runs
}
// try-with-resources (auto-close)
try (InputStream in = new FileInputStream(f)) {
// in closed automatically
}

SQL Cheatsheet

Quick reference for SQL queries, joins & window functions

CRUD
SELECT * FROM users WHERE active = 1;
SELECT name, email FROM users ORDER BY name ASC;
SELECT * FROM users LIMIT 10 OFFSET 20;
INSERT INTO users (name, email) VALUES ('A', 'a@b.com');
UPDATE users SET age = 29 WHERE id = 1;
DELETE FROM users WHERE active = 0;
Filtering
WHERE age BETWEEN 18 AND 30
WHERE name LIKE 'A%' -- starts with A
WHERE name LIKE '%aftab%' -- contains aftab
WHERE role IN ('admin', 'mod')
WHERE email IS NULL
WHERE email IS NOT NULL
WHERE age > 18 AND city = 'Delhi'
WHERE age < 18 OR role = 'admin'
WHERE NOT active = 0
Aggregate Functions
COUNT(*)Total rows
COUNT(DISTINCT col)Unique values
SUM(col)Total of values
AVG(col)Average
MAX(col)Largest value
MIN(col)Smallest value
GROUP BY colGroup rows by column
HAVING COUNT(*) > 2Filter groups
JOINs
SELECT u.name, o.total
FROM users u
INNER JOIN orders o ON u.id = o.user_id; -- matched only
LEFT JOIN orders o ON u.id = o.user_id; -- all users
RIGHT JOIN users u ON u.id = o.user_id; -- all orders
FULL OUTER JOIN ... ON ...; -- all from both
CROSS JOIN products; -- cartesian
Subqueries & CTEs
SELECT * FROM users
WHERE id IN (SELECT user_id FROM orders WHERE total > 1000);
-- CTE (Common Table Expression)
WITH top_orders AS (
SELECT user_id, SUM(total) AS revenue
FROM orders GROUP BY user_id
)
SELECT u.name, t.revenue
FROM users u JOIN top_orders t ON u.id = t.user_id
ORDER BY t.revenue DESC;
Window Functions
SELECT name, salary,
RANK() OVER (PARTITION BY dept ORDER BY salary DESC),
ROW_NUMBER() OVER (ORDER BY salary DESC),
LAG(salary,1) OVER (ORDER BY salary),
LEAD(salary,1) OVER (ORDER BY salary),
SUM(salary) OVER (PARTITION BY dept)
FROM employees;

MongoDB Shell Cheatsheet

Quick reference for mongosh commands & operators

CRUD
db.col.insertOne({ name: "Aftab" });
db.col.insertMany([{...},{...}]);
db.col.find({ age: { $gt: 18 } });
db.col.findOne({ email: "a@b.com" });
db.col.updateOne({_id:id},{$set:{age:29}});
db.col.updateMany({active:false},{$set:{deleted:true}});
db.col.deleteOne({ _id: id });
db.col.deleteMany({ active: false });
db.col.countDocuments({ role: "admin" });
Query Operators
$eq / $neEqual / not equal
$gt / $gteGreater than / or equal
$lt / $lteLess than / or equal
$in / $ninIn / not in array
$and / $or / $norLogical operators
$existsField exists check
$regexPattern match
$allArray contains all values
$elemMatchArray element conditions
$sizeArray length
Update Operators
$setSet field value
$unsetRemove field
$incIncrement / decrement
$pushAdd to array
$pullRemove from array
$addToSetPush if not exists
$popRemove first/last element
$renameRename field
$mulMultiply field value
Aggregation
db.col.aggregate([
{ $match: { status: "active" } },
{ $group: { _id: "$dept", cnt: { $sum: 1 } } },
{ $sort: { cnt: -1 } },
{ $limit: 5 },
{ $project: { _id: 0, dept: "$_id", cnt: 1 } },
{ $lookup: { from:"users", localField:"userId",
foreignField:"_id", as:"user" } },
{ $unwind: "$items" }
]);

React Hooks Cheatsheet

Quick reference for all built-in React hooks

useState
const [count, setCount] = useState(0);
const [user, setUser] = useState(null);
const [form, setForm] = useState({ name:'', age:0 });
setCount(c => c + 1); // functional update
setForm(f => ({ ...f, name: 'Aftab' }));
useEffect
useEffect(() => {}, []); // run once
useEffect(() => {}, [id]); // run when id changes
useEffect(() => {}); // run on every render
useEffect(() => {
const sub = subscribe();
return () => sub.unsubscribe(); // cleanup
}, []);
useRef / useContext
const inputRef = useRef(null); // DOM ref
inputRef.current.focus();
const counter = useRef(0); // mutable value (no re-render)
counter.current++;
const ThemeCtx = createContext('light');
const theme = useContext(ThemeCtx); // consume context
<ThemeCtx.Provider value="dark">...</ThemeCtx.Provider>
useMemo / useCallback
const sorted = useMemo(
() => items.sort((a,b) => a-b),
[items] // recompute only when items changes
);
const handleClick = useCallback(
(id) => dispatch(select(id)),
[dispatch] // stable reference
);
useReducer
const reducer = (state, action) => {
switch(action.type) {
case 'inc': return { count: state.count + 1 };
default: return state;
}
};
const [state, dispatch] = useReducer(reducer, { count: 0 });
dispatch({ type: 'inc' });
Custom Hooks
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(url).then(r => r.json())
.then(setData)
.finally(() => setLoading(false));
}, [url]);
return { data, loading };
}
const { data, loading } = useFetch('/api/users');

Spring Boot Annotations Cheatsheet

Quick reference for the most important Spring Boot annotations

Core / Application
@SpringBootApplicationMain class — enables auto-config, component scan
@ConfigurationMarks a bean configuration class
@BeanDeclares a Spring-managed bean (method-level)
@ComponentGeneric Spring component
@ServiceBusiness logic layer
@RepositoryDAO layer — translates DB exceptions
@PrimaryDefault bean when multiple candidates
@ConditionalConditional bean registration
Dependency Injection
@AutowiredInject dependency (prefer constructor DI)
@Qualifier("name")Specify which bean to inject
@Value("${key}")Inject property from application.properties
@ConfigurationProperties(prefix="app")Bind config block to POJO
REST Controllers
@RestController@Controller + @ResponseBody
@RequestMapping("/api")Base path for controller
@GetMapping("/users")HTTP GET
@PostMapping("/users")HTTP POST
@PutMapping("/users/{id}")HTTP PUT
@DeleteMapping("/users/{id}")HTTP DELETE
@PatchMapping("/users/{id}")HTTP PATCH
@PathVariable Long idURL path param
@RequestParam String qQuery string param
@RequestBody User userJSON body → object
@ResponseStatus(201)Set HTTP status code
JPA / Persistence
@EntityMaps class to DB table
@Table(name="users")Custom table name
@IdPrimary key field
@GeneratedValueAuto-generate PK (IDENTITY/SEQUENCE)
@Column(nullable=false)Column constraints
@OneToMany(mappedBy="user")One-to-many relation
@ManyToOneMany-to-one relation
@JoinColumn(name="user_id")FK column
@TransientField not mapped to column
Validation
@Valid / @ValidatedTrigger validation on request body
@NotNullMust not be null
@NotBlankNot null & not blank string
@Size(min,max)String / collection size
@Min / @MaxNumber range
@EmailValid email format
@Pattern(regexp="...")Regex constraint
@PositiveNumber must be > 0
AOP & Transactions
@TransactionalWrap method in DB transaction
@Transactional(readOnly=true)Optimize read-only queries
@AsyncRun method in thread pool
@Scheduled(fixedRate=5000)Run every 5 seconds
@Scheduled(cron="0 0 * * * *")Cron-based scheduling
@EnableSchedulingEnable scheduler (on @Config class)
@EnableAsyncEnable async (on @Config class)

Git Cheatsheet

Quick reference for everyday Git commands

Setup & Init
git config --global user.name "Aftab"
git config --global user.email "a@b.com"
git init # init repo
git clone URL # clone repo
git clone URL --depth 1 # shallow clone
Stage & Commit
git status # working tree status
git add file.txt # stage file
git add . # stage all changes
git diff # unstaged diff
git diff --staged # staged diff
git commit -m "message"
git commit --amend # modify last commit
Branches
git branch # list branches
git branch feature/x # create branch
git checkout feature/x # switch
git checkout -b feature/x # create + switch
git switch main # modern switch
git branch -d feature/x # delete branch
git merge feature/x # merge into current
git rebase main # rebase onto main
Remote
git remote -v # list remotes
git remote add origin URL
git push origin main
git push -u origin feature/x # set upstream
git pull # fetch + merge
git fetch origin # fetch only
git push --force-with-lease # safe force push
Undo & Reset
git restore file.txt # discard working changes
git restore --staged f # unstage file
git reset HEAD~1 # undo last commit (keep changes)
git reset --hard HEAD~1 # undo + discard changes
git revert <sha> # create undo commit (safe)
git stash # stash changes
git stash pop # restore stashed changes
Log & Search
git log --oneline
git log --graph --oneline --all
git log -p file.txt # history of file
git blame file.txt # who changed each line
git show <sha> # show a commit
git grep "searchterm" # search in files
git log --grep="fix" # search commit msgs

Docker Cheatsheet

Quick reference for Docker CLI, images, containers & Compose

Images
docker pull nginx # pull from registry
docker images # list images
docker rmi nginx # remove image
docker build -t myapp:1.0 . # build from Dockerfile
docker tag myapp myrepo/myapp:1.0
docker push myrepo/myapp:1.0
docker history myapp # image layers
Containers
docker run -d -p 8080:80 nginx # run detached
docker run -it ubuntu bash # interactive
docker run --name mycon myapp
docker run --rm myapp # auto-remove on exit
docker ps # running containers
docker ps -a # all containers
docker stop mycon / docker start mycon
docker rm mycon # remove container
docker exec -it mycon bash # shell into container
docker logs mycon -f # follow logs
Dockerfile
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
RUN npm run build
EXPOSE 3000
ENV NODE_ENV=production
USER node
CMD ["node", "index.js"]
Docker Compose
docker compose up -d # start all services
docker compose down # stop & remove
docker compose down -v # also remove volumes
docker compose logs -f app # follow service logs
docker compose exec app sh # shell into service
docker compose build # rebuild images
docker compose ps # list services
Volumes & Networks
docker volume create mydata
docker run -v mydata:/data myapp # named volume
docker run -v $(pwd):/app myapp # bind mount
docker volume ls / docker volume rm mydata
docker network create mynet
docker run --network mynet myapp
docker network ls
Compose File
services:
app:
build: .
ports: ["3000:3000"]
environment:
- MONGO_URI=mongodb://mongo:27017/db
depends_on: [mongo]
mongo:
image: mongo:7
volumes: ["mongodata:/data/db"]
volumes:
mongodata:

Linux Commands Cheatsheet

Quick reference for essential Linux / Bash commands

Navigation & Files
pwd # print working directory
ls -la # list files (long + hidden)
cd /path / cd ~ # change dir / home
mkdir -p a/b/c # create nested dirs
touch file.txt # create empty file
cp -r src/ dest/ # recursive copy
mv old.txt new.txt # move / rename
rm -rf folder/ # remove recursively
find . -name "*.log" # find files
File Content
cat file.txt # print file
less file.txt # paginate (q to quit)
head -n 20 file.txt # first 20 lines
tail -n 20 file.txt # last 20 lines
tail -f app.log # follow log file
grep "error" log.txt # search in file
grep -r "pattern" ./ # recursive search
wc -l file.txt # line count
sort file.txt | uniq # sort + deduplicate
Permissions
chmod 755 script.sh # rwxr-xr-x
chmod +x script.sh # add execute
chown user:group file
ls -l # shows permissions
sudo command # run as root
su - username # switch user
755 = rwxr-xr-x (owner=full, others=rx)
644 = rw-r--r-- (owner=rw, others=r)
Processes
ps aux # all running processes
top / htop # interactive monitor
kill -9 PID # force kill process
pkill -f "node" # kill by name
command & # run in background
jobs # list background jobs
fg %1 # bring job to foreground
nohup cmd > out.log & # persist after logout
Networking
curl -X GET https://api.example.com/users
curl -X POST -H "Content-Type: application/json" \
-d '{"name":"Aftab"}' https://api.com/users
wget https://example.com/file.zip
ping google.com
netstat -tuln # listening ports
ss -tuln # modern netstat
lsof -i :3000 # what's on port 3000
scp file user@host:/path # secure copy
Disk & System
df -h # disk usage (human readable)
du -sh folder/ # folder size
free -h # memory usage
uname -a # system info
uptime # system uptime + load
env # list env variables
export VAR=value # set env variable
echo $HOME # print env var
history | grep git # search command history

Regex Cheatsheet

Quick reference for regular expression syntax

Character Classes
.Any char except newline
\dDigit [0-9]
\DNon-digit
\wWord char [a-zA-Z0-9_]
\WNon-word char
\sWhitespace (space, tab, newline)
\SNon-whitespace
[abc]a or b or c
[^abc]Not a, b, or c
[a-z]a through z
[A-Za-z0-9]Alphanumeric
Quantifiers
*0 or more (greedy)
+1 or more (greedy)
?0 or 1 (optional)
{3}Exactly 3
{2,5}2 to 5
{3,}3 or more
*?Lazy (non-greedy) 0 or more
+?Lazy 1 or more
Anchors & Boundaries
^Start of string
$End of string
\bWord boundary
\BNon-word boundary
(?=...)Positive lookahead
(?!...)Negative lookahead
(?<=...)Positive lookbehind
(?<!...)Negative lookbehind
Groups & Alternation
(abc)Capturing group
(?:abc)Non-capturing group
(?<name>abc)Named capturing group
a|ba or b (alternation)
\1Backreference to group 1
Common Patterns
// Email
/^[\w.+-]+@[\w-]+\.[a-z]{2,}$/i
// URL
/https?:\/\/[\w.-]+(?:\/[\w./?=%&-]*)?/i
// Phone (India)
/^(\+91)?[6-9]\d{9}$/
// Date YYYY-MM-DD
/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/
// Password (min 8, upper+lower+digit)
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/
JS Regex Methods
const re = /pattern/flags; // flags: g i m s
re.test("string") // → true/false
"str".match(re) // → array / null
"str".matchAll(re) // → iterator (use g flag)
"str".search(re) // → index or -1
"str".replace(re, "new")
"str".replaceAll(re, "new") // use g flag
"str".split(re) // → array