Javascript RegExp

Javascript RegExp

JavaScript RegExp (Regular Expressions)

Regular Expressions (RegExp) in JavaScript allow pattern matching and text manipulation. They are commonly used for validating input, searching, and replacing text.

1️⃣ Creating a Regular Expression

There are two ways to create a RegExp in JavaScript:

1.1 Using Literal Syntax (Recommended)

const regex = /hello/;

1.2 Using the RegExp Constructor

const regex = new RegExp("hello");

2️⃣ Flags in Regular Expressions

Flags modify how a regex behaves:

FlagMeaning
gGlobal search (find all matches, not just the first one)
iCase-insensitive search
mMulti-line search
sAllows . to match newlines
uEnables Unicode support
ySticky search (matches from last index)

Example:

const regex = /hello/gi; // Case insensitive and global search

3️⃣ Common RegExp Methods

3.1 test() – Check if Pattern Exists

Returns true if the pattern exists in the string, else false.

const regex = /world/; console.log(regex.test("Hello world")); // true console.log(regex.test("Hello there")); // false

3.2 match() – Get Matches

Returns an array of matches or null if no match is found.

const str = "The rain in Spain falls mainly in the plain."; const result = str.match(/ain/g); console.log(result); // ["ain", "ain", "ain"]

3.3 search() – Find Position of First Match

Returns the index of the first match or -1 if no match is found.

const str = "The rain in Spain"; console.log(str.search(/Spain/)); // 12 console.log(str.search(/France/)); // -1

3.4 replace() – Replace Matching Text

const str = "I love JavaScript"; const newStr = str.replace(/JavaScript/, "Python"); console.log(newStr); // "I love Python"

With a global flag (g):

const str = "JavaScript is great. I love JavaScript."; const newStr = str.replace(/JavaScript/g, "Python"); console.log(newStr); // "Python is great. I love Python."

3.5 split() – Split a String Using a Pattern

const str = "apple,banana,grape,orange"; const arr = str.split(/,/); console.log(arr); // ["apple", "banana", "grape", "orange"]

4️⃣ Regular Expression Patterns

4.1 Character Classes

PatternMeaningExample
\dMatches a digit (0-9)/\d/"abc123"["1"]
\DMatches a non-digit/\D/"123abc"["a"]
\wMatches a word character (a-z, A-Z, 0-9, _)/\w/"Hello_123"["H"]
\WMatches a non-word character/\W/"Hello!"["!"]
\sMatches whitespace (space, tab, newline)/\s/"hello world"[" "]
\SMatches non-whitespace/\S/" " → No match

4.2 Quantifiers

QuantifierMeaningExample
+One or more times/\d+/"123abc"["123"]
*Zero or more times/\d*/"abc"[""]
?Zero or one time/colou?r/"color"["color"]
{n}Exactly n times/\d{3}/"1234"["123"]
{n,}At least n times/\d{2,}/"12345"["12345"]
{n,m}Between n and m times/\d{2,4}/"12345"["1234"]

4.3 Anchors

AnchorMeaningExample
^Start of a string/^hello/"hello world"["hello"]
$End of a string/world$/"hello world"["world"]
\bWord boundary/\bcar\b/"car is here"["car"]

4.4 Groups and Alternation

PatternMeaningExample
(abc)Capturing group/(\d+)-(\d+)/"123-456"["123-456", "123", "456"]
(?:abc)Non-capturing group`/(?:hello
``Alternation (OR)

5️⃣ Examples of Using Regular Expressions

5.1 Validate an Email

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; console.log(emailRegex.test("user@example.com")); // true console.log(emailRegex.test("invalid-email")); // false

5.2 Validate a Phone Number

const phoneRegex = /^\+?[0-9]{10,15}$/; console.log(phoneRegex.test("+1234567890")); // true console.log(phoneRegex.test("123-456-7890")); // false

5.3 Validate a Strong Password

A strong password must have at least 8 characters, one uppercase letter, one lowercase letter, one number, and one special character.

const passwordRegex = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/; console.log(passwordRegex.test("Str0ng@Pass")); // true console.log(passwordRegex.test("weakpass")); // false

5.4 Extract Numbers from a String

const str = "Order #1234 costs $99.50"; const numbers = str.match(/\d+/g); console.log(numbers); // ["1234", "99", "50"]

Conclusion

JavaScript Regular Expressions (RegExp) are powerful for text searching, validation, and manipulation. By mastering character classes, quantifiers, anchors, and groups, you can perform complex pattern matching with ease.

Let me know if you need more examples! 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close