JavaScript RegExp

JavaScript Tutorial

JavaScript RegExp

In JavaScript RegExp is a pattern used to search, match, and manipulate text. It helps validate data like email, phone numbers, passwords, etc.

You can create a RegExp in two ways:


RegExp Methods

test() — Returns true or false


exec() — Returns match details or null


 String Methods with RegExp

MethodDescriptionExample
match()Finds matches"Hello".match(/l/g)
replace()Replace matched text"Hello".replace(/l/g, "*")
search()Returns first match index"Hello".search(/e/)
split()Split using regex"a,b;c".split(/[,;]/)

Example:


RegExp Modifiers (Flags)

FlagMeaningExample
gGlobal search/a/g
iCase-insensitive/apple/i
mMulti-line/^hello/m

Example:


RegExp Special Characters

SymbolMeaningExample
.Any character/h.t/ → “hat”, “hot”
^Begins with/^hello/
$Ends with/world$/
\dDigits 0–9/\d/
\wAlphanumeric/\w/
\sWhitespace/\s/
+One or more/a+/
*Zero or more/a*/
{n}Exact count/\d{3}/ → 3 digits
``OR

Useful Examples

 Validate Email


 Validate Phone Number (Indian Example)


 Strong Password Check


Summary

FeatureExample
Create RegExp/pattern/
Test textregex.test(text)
Search & replacetext.replace(regex, value)
Validate inputEmails, phone numbers, passwords

You may also like...