JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS String Methods


JavaScript provides a wide range of string methods that make it easy to manipulate and work with text. Whether you are validating user input, formatting names, searching within text, or converting data types, string methods help you perform these operations efficiently. Understanding and using these methods effectively is crucial for building interactive and dynamic web applications.

In this chapter, you will learn about common string methods, how to use them with practical examples, common mistakes, best practices, and real-world applications.

Why String Methods Are Important

String methods allow you to:

  • Transform text to uppercase or lowercase

  • Search and extract parts of a string

  • Replace or remove content

  • Trim unwanted spaces

  • Split strings into arrays

  • Format text for display

  • Validate user input

Using string methods reduces code complexity, ensures readability, and avoids manual string manipulation mistakes.

Commonly Used String Methods

1. toUpperCase() and toLowerCase()

These methods convert strings to uppercase or lowercase, respectively.

let student = "Ananya";
console.log(student.toUpperCase()); // ANANYA
console.log(student.toLowerCase()); // ananya

These methods are useful for standardizing input or performing case-insensitive comparisons.

2. charAt()

Returns the character at a specific index.

let name = "Riya";
console.log(name.charAt(0)); // R
console.log(name.charAt(2)); // y

3. includes()

Checks if a string contains a specific substring. Returns true or false.

let message = "Welcome Mira to the course";
console.log(message.includes("Mira")); // true
console.log(message.includes("Ananya")); // false

This is commonly used for search functionality or validation.

4. indexOf() and lastIndexOf()

Finds the index of a substring. Returns -1 if not found.

let student = "Diya Sharma";
console.log(student.indexOf("Sharma")); // 5
console.log(student.lastIndexOf("a")); // 9

5. slice()

Extracts a part of the string and returns it as a new string.

let student = "Sneha Gupta";
let firstName = student.slice(0, 5);
console.log(firstName); // Sneha

You can also use negative indices:

let lastName = student.slice(-5);
console.log(lastName); // Gupta

6. substring()

Similar to slice() but does not accept negative indices.

let student = "Kavya Patel";
console.log(student.substring(0, 5)); // Kavya

7. replace()

Replaces a specified value with another. By default, only replaces the first occurrence.

let student = "Ananya is learning JavaScript";
let updated = student.replace("Ananya", "Riya");
console.log(updated); // Riya is learning JavaScript

For global replacement, use a regular expression with the g flag:

let text = "Mira and Mira are friends";
let newText = text.replace(/Mira/g, "Diya");
console.log(newText); // Diya and Diya are friends

8. trim()

Removes whitespace from both ends of a string.

let input = "   Sneha   ";
console.log(input.trim()); // Sneha

9. split()

Splits a string into an array based on a specified separator.

let students = "Ananya,Riya,Mira";
let studentArray = students.split(",");
console.log(studentArray); // ["Ananya", "Riya", "Mira"]

10. concat()

Joins two or more strings.

let firstName = "Diya";
let lastName = "Sharma";
let fullName = firstName.concat(" ", lastName);
console.log(fullName); // Diya Sharma

11. startsWith() and endsWith()

Checks if a string starts or ends with a specific substring.

let name = "Ishita Gupta";
console.log(name.startsWith("Ish")); // true
console.log(name.endsWith("Gupta")); // true

Practical Examples

Example 1: Formatting Student Names

let students = ["riya", "mira", "ananya"];
students = students.map(name => name.charAt(0).toUpperCase() + name.slice(1));
console.log(students); // ["Riya", "Mira", "Ananya"]

Example 2: Checking Keywords in Messages

let message = "Diya submitted her assignment";
if (message.includes("Diya")) {
    console.log("Message contains Diya");
}

Example 3: Extracting First Names

let fullName = "Sneha Gupta";
let firstName = fullName.slice(0, fullName.indexOf(" "));
console.log(firstName); // Sneha

Example 4: Splitting Names into Arrays

let studentNames = "Ananya,Riya,Diya,Mira";
let namesArray = studentNames.split(",");
console.log(namesArray);

Example 5: Removing Extra Spaces

let input = "   Kavya   ";
let trimmedInput = input.trim();
console.log(trimmedInput); // Kavya

Common Mistakes

  • Forgetting that string methods return a new string; original string remains unchanged

  • Using negative indices with substring() (it does not support negative numbers)

  • Ignoring case sensitivity when comparing strings

  • Using replace() without g flag when multiple occurrences exist

  • Not validating input before applying string methods

Best Practices

  • Use template literals for combining strings instead of concat() or +

  • Always handle empty strings and whitespace

  • Prefer includes() over indexOf() for readability

  • Use trim() when working with user input

  • Chain string methods carefully to avoid unexpected results

Real-World Applications

String methods are widely used in:

  • Form input validation and formatting

  • Displaying messages and notifications

  • Searching and filtering content

  • Processing API responses

  • Preparing text for storage or display

  • Generating user-friendly content dynamically

Summary of JS String Methods

JavaScript string methods provide powerful tools to manipulate and handle textual data efficiently. Methods like toUpperCase(), slice(), replace(), split(), and trim() allow developers to perform common operations quickly and reliably. Mastering string methods is essential for data processing, UI display, user input handling, and many other real-world applications.


Practice Questions

Q1. How do you extract "Script" from the string "JavaScript" using slice()?

Q2. How do you replace "Hello" with "Hi" in the string "Hello World"?

Q3. How do you convert "good morning" to uppercase?

Q4. How do you trim the spaces from both sides of " welcome "?

Q5. Which method will split "apple,banana,grape" into an array of fruits?

Q6. How do you pad the string "9" to become "009" using a string method?

Q7. What method can you use to repeat "ha" 4 times to form "hahahaha"?

Q8. How do you replace all occurrences of "a" with "*", in "a-a-a"?

Q9. How do you extract the substring "ava" from "JavaScript" using substring()?

Q10. What method will convert "JAVASCRIPT" to lowercase letters?


Try a Short Quiz.

No quizzes available.


JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top