-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
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.
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.
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.
charAt()Returns the character at a specific index.
let name = "Riya";
console.log(name.charAt(0)); // R
console.log(name.charAt(2)); // y
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.
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
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
substring()Similar to slice() but does not accept negative indices.
let student = "Kavya Patel";
console.log(student.substring(0, 5)); // Kavya
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
trim()Removes whitespace from both ends of a string.
let input = " Sneha ";
console.log(input.trim()); // Sneha
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"]
concat()Joins two or more strings.
let firstName = "Diya";
let lastName = "Sharma";
let fullName = firstName.concat(" ", lastName);
console.log(fullName); // Diya Sharma
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
let students = ["riya", "mira", "ananya"];
students = students.map(name => name.charAt(0).toUpperCase() + name.slice(1));
console.log(students); // ["Riya", "Mira", "Ananya"]
let message = "Diya submitted her assignment";
if (message.includes("Diya")) {
console.log("Message contains Diya");
}
let fullName = "Sneha Gupta";
let firstName = fullName.slice(0, fullName.indexOf(" "));
console.log(firstName); // Sneha
let studentNames = "Ananya,Riya,Diya,Mira";
let namesArray = studentNames.split(",");
console.log(namesArray);
let input = " Kavya ";
let trimmedInput = input.trim();
console.log(trimmedInput); // Kavya
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
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
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
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.
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?
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
