Skip to main content

Python type() Function

When learning Python, you will work with different types of data, such as numbers, text, decimal values, and Boolean values. Python provides several built-in functions to help you work with these data types. One of the most useful functions is the type() function . The type() function tells you the data type of a value or variable. It helps you understand what kind of data Python is working with and can make debugging your programs easier. For example, consider these variables: age = 20 price = 99.50 name = "Rahul" is_student = True Although all four variables store data, their data types are different. Python allows us to check these types using type() . Let's understand how it works with simple examples. 1. What Is the type() Function in Python? The type() function is a built-in Python function that returns information about the type of an object. In beginner-level programming, you can use it to check whether a value is an integer, a floating-point number, a string,...

JavaScript Regular Expressions (RegEx) – Complete Guide for Beginners

In modern web development, applications frequently need to work with text.

Examples include:

  • Validating email addresses

  • Checking phone numbers

  • Verifying passwords

  • Searching text

  • Replacing words

  • Filtering user input

Imagine creating a registration form.

You need to verify:

Is the email valid?

Is the phone number correct?

Does the password meet requirements?

Writing complex conditions for each validation would be difficult.

To solve this problem, JavaScript provides Regular Expressions (RegEx).

Regular Expressions allow developers to search, match, validate, and manipulate text efficiently.

In this article, we will learn:

  • What RegEx is

  • Why RegEx is useful

  • Creating Regular Expressions

  • Pattern Matching

  • Special Characters

  • Character Classes

  • Quantifiers

  • Validation

  • Search and Replace

  • Real-world Examples


What is RegEx?

RegEx stands for:

Regular Expression

A Regular Expression is a pattern used to match text.

Think of it as a search rule.

Example:

Find all words containing "Java"

RegEx can perform this task instantly.


Real-Life Example

Suppose a teacher wants to find all students whose names begin with "A".

Without RegEx:

Check every name manually

With RegEx:

Apply Pattern

A*

Matching names are found automatically.


Why RegEx is Important

RegEx helps with:

  • Validation

  • Searching

  • Filtering

  • Text Processing

  • Data Cleaning

Almost every website uses RegEx.


Creating a Regular Expression

There are two ways.


Method 1: Literal Notation

let pattern =
/hello/;

Method 2: Constructor

let pattern =
new RegExp("hello");

Both are valid.


Testing a Pattern

The test() method checks whether a match exists.

Example:

let pattern =
/hello/;

console.log(
pattern.test("hello world")
);

Output:

true

Example

let pattern =
/hello/;

console.log(
pattern.test("JavaScript")
);

Output:

false

Because "hello" is not present.


Case Sensitivity

By default:

/hello/

matches:

hello

but not:

HELLO

Ignore Case Flag

Use:

/hello/i

Example:

let pattern =
/hello/i;

console.log(
pattern.test("HELLO")
);

Output:

true

Common Flags

FlagMeaning
iIgnore Case
gGlobal Search
mMulti-line Search

The match() Method

Used to retrieve matching text.

Example:

let text =
"JavaScript is awesome";

console.log(
text.match(/JavaScript/)
);

Output:

["JavaScript"]

The search() Method

Returns the position of a match.

Example:

let text =
"I love JavaScript";

console.log(
text.search(/JavaScript/)
);

Output:

7

The replace() Method

Replaces matching text.

Example:

let text =
"Hello World";

let result =
text.replace(
/World/,
"JavaScript"
);

console.log(result);

Output:

Hello JavaScript

Character Classes

Character classes define groups of characters.


Digits

\d

Means:

Any digit 0–9

Example:

console.log(
/\d/.test("5")
);

Output:

true

Non-Digits

\D

Means:

Any non-digit character

Word Characters

\w

Matches:

A-Z

a-z

0-9

_

Non-Word Characters

\W

Matches special symbols.


Whitespace

\s

Matches:

Space

Tab

Newline

Non-Whitespace

\S

Matches anything except whitespace.


Character Sets

Example:

/[abc]/

Matches:

a

b

c

Example

console.log(
/[abc]/.test("banana")
);

Output:

true

Because "a" exists.


Range Matching

/[A-Z]/

Matches:

Any uppercase letter

Example

console.log(
/[A-Z]/.test("HELLO")
);

Output:

true

Quantifiers

Quantifiers specify how many times a character should appear.


The * Quantifier

a*

Means:

0 or more a's

Example

Matches:

a

aa

aaa

The + Quantifier

a+

Means:

1 or more a's

Example

Matches:

a

aa

aaa

but not:

(empty)

The ? Quantifier

a?

Means:

0 or 1 occurrence

Exact Quantity

\d{5}

Means:

Exactly 5 digits

Example

console.log(
/\d{5}/.test("12345")
);

Output:

true

Start and End Anchors


Start Anchor

^

Matches beginning.

Example:

/^Hello/

Matches:

Hello World

but not:

World Hello

End Anchor

$

Matches end.

Example:

/World$/

Matches:

Hello World

Email Validation

Basic email pattern:

let emailPattern =
/^[^\s@]+@[^\s@]+\.[^\s@]+$/;

Example

console.log(
emailPattern.test(
"abc@gmail.com"
)
);

Output:

true

Phone Number Validation

10-digit number:

let phonePattern =
/^\d{10}$/;

Example:

console.log(
phonePattern.test(
"9876543210"
)
);

Output:

true

Password Validation

At least 8 characters:

let passwordPattern =
/^.{8,}$/;

Example:

console.log(
passwordPattern.test(
"mypassword"
)
);

Output:

true

Practical Example – Name Validation

Only alphabets allowed:

let namePattern =
/^[A-Za-z]+$/;

Example:

console.log(
namePattern.test(
"Rahul"
)
);

Output:

true

Global Search

Using:

g

Example:

let text =
"cat dog cat";

console.log(
text.match(/cat/g)
);

Output:

["cat","cat"]

Splitting Text

Example:

let text =
"Apple,Mango,Orange";

let fruits =
text.split(",");

Output:

["Apple","Mango","Orange"]

Practical Project – Email Checker

function validateEmail(email)
{
    let pattern =
    /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

    return pattern.test(email);
}

console.log(
validateEmail(
"test@gmail.com"
)
);

Output:

true

Practical Project – Mobile Number Validator

function validatePhone(phone)
{
    let pattern =
    /^\d{10}$/;

    return pattern.test(phone);
}

console.log(
validatePhone(
"9876543210"
)
);

Output:

true

Common RegEx Patterns

PurposePattern
Email/^[^\s@]+@[^\s@]+.[^\s@]+$/
Phone/^\d{10}$/
Only Letters/^[A-Za-z]+$/
Only Numbers/^\d+$/
Password 8+/^.{8,}$/

Real-Life Applications

RegEx is used in:

  • Login Forms

  • Registration Systems

  • Search Engines

  • Password Validation

  • Data Cleaning

  • Text Editors

  • Chat Applications

Websites and applications use RegEx daily to validate user input and process text efficiently.


Common Mistakes Beginners Make

Forgetting Escape Characters

Wrong:

/.
/

Correct:

/\./

Missing Anchors

Wrong:

\d{10}

May match inside larger strings.

Correct:

/^\d{10}$/

Using Complex Patterns Too Early

Start with simple patterns and gradually build complex ones.


Advantages of RegEx

  • Powerful text matching

  • Fast validation

  • Compact code

  • Flexible searching

  • Essential for web development


Conclusion

Regular Expressions are one of the most powerful tools in JavaScript. They allow developers to search, validate, filter, and manipulate text efficiently.

Comments

Popular posts from this blog

Understanding Comments in Java: A Beginner’s Guide

When learning Java programming, one of the first concepts you’ll come across is comments . Comments may not affect how a program runs, but they play a crucial role in making code more understandable, readable, and maintainable. Let’s dive deeper into what comments are, why they’re important, and the different types of comments in Java. What are Comments in Java? A comment in Java is a piece of text written within a program that is ignored by the compiler . In other words, comments are notes for humans, not instructions for machines. They help developers explain the purpose of code, describe logic, or temporarily disable certain lines of code without deleting them. Why are Comments Important? ๐Ÿ“Œ Readability – Comments make code easier to understand for you and others. ๐Ÿ“Œ Maintenance – When you revisit your code after months, comments remind you what you were doing. ๐Ÿ“Œ Collaboration – In team projects, comments explain code to fellow developers. ๐Ÿ“Œ Debugging – You c...

Java Program to Check Voting Eligibility

In this program, we’ll take the user’s age as input and check whether the person is eligible to vote or not. In India, the minimum age required to vote is 18 years . ๐Ÿ’ป Program Code // Java Program to Check Voting Eligibility import java.util.Scanner; public class VotingEligibility { public static void main(String[] args) { // Create Scanner object to take input from user Scanner sc = new Scanner(System.in); // Ask user to enter age System.out.print("Enter your age: "); int age = sc.nextInt(); // Check eligibility if (age >= 18) { System.out.println("You are eligible to vote."); } else { System.out.println("You are not eligible to vote yet."); System.out.println("You can vote after " + (18 - age) + " year(s)."); } sc.close(); // Close the scanner } } ๐Ÿง  Explanation import java.util.Scanner; → Imp...

Java Program to Calculate Total Marks and Average of Five Subjects

๐Ÿ’ก Program Explanation In this program: The user will input marks of five subjects . The program will calculate the total marks and average . It will then display both results clearly. ๐Ÿง‘‍๐Ÿ’ป Java Code: // Java Program to Calculate Total Marks and Average of Five Subjects import java.util.Scanner; // Importing Scanner class for user input public class TotalAndAverage { public static void main(String[] args) { // Creating Scanner object to take input from user Scanner sc = new Scanner(System.in); // Declaring variables for five subjects double subject1, subject2, subject3, subject4, subject5; // Taking marks input for each subject System.out.print("Enter marks of Subject 1: "); subject1 = sc.nextDouble(); System.out.print("Enter marks of Subject 2: "); subject2 = sc.nextDouble(); System.out.print("Enter marks of Subject 3: "); subject3 = sc.nextDo...