JavaScript Strings and String Methods
A string is a sequence of characters used to represent text. Strings are one of the most frequently used data types in JavaScript — everything from a person's name to a full web page address is stored as a string.
JavaScript provides a rich set of built-in string methods to manipulate, search, and format text efficiently.
Creating Strings
Strings can be created using single quotes, double quotes, or backticks (template literals).
let name1 = 'Ananya'; // Single quotes
let name2 = "Rajan"; // Double quotes
let greeting = `Hello, World!`; // Backticks (Template literal)All three work the same way. Backticks are the modern choice because they support embedded expressions.
String Length
let text = "JavaScript";
console.log(text.length); // 10Accessing Characters
Individual characters in a string are accessed using their index (starting from 0).
let word = "Hello";
console.log(word[0]); // H
console.log(word[4]); // o
// charAt() method
console.log(word.charAt(1)); // eString Concatenation
Strings are joined using the + operator or the concat() method.
let firstName = "Vikas";
let lastName = "Sharma";
let fullName = firstName + " " + lastName;
console.log(fullName); // Vikas Sharma
// Using concat()
let result = firstName.concat(" ", lastName);
console.log(result); // Vikas SharmaTemplate Literals (ES6)
Template literals use backticks and allow embedding variables directly into strings using ${ }. This is much cleaner than string concatenation.
let product = "Laptop";
let price = 55000;
console.log(`The ${product} costs ₹${price}.`);
// Output: The Laptop costs ₹55000.Multi-line Strings with Template Literals
let message = `Dear Customer,
Thank you for your order.
Your item will be delivered within 3 days.
Regards,
Support Team`;
console.log(message);Case Conversion Methods
toUpperCase() — Convert to Uppercase
let text = "hello world";
console.log(text.toUpperCase()); // HELLO WORLDtoLowerCase() — Convert to Lowercase
let text = "JAVASCRIPT IS FUN";
console.log(text.toLowerCase()); // javascript is funRemoving Whitespace
trim() — Remove Spaces from Both Ends
let input = " hello ";
console.log(input.trim()); // "hello"
console.log(input.trimStart()); // "hello "
console.log(input.trimEnd()); // " hello"Searching in Strings
includes() — Check if a Substring Exists
let sentence = "JavaScript is a popular language";
console.log(sentence.includes("popular")); // true
console.log(sentence.includes("Python")); // falsestartsWith() and endsWith()
let url = "https://estudy247.com";
console.log(url.startsWith("https")); // true
console.log(url.endsWith(".com")); // trueindexOf() — Find Position of a Substring
let text = "Learn JavaScript with us";
console.log(text.indexOf("JavaScript")); // 6
console.log(text.indexOf("Python")); // -1 (not found)lastIndexOf() — Find Last Occurrence
let text = "apple mango apple banana apple";
console.log(text.lastIndexOf("apple")); // 19 (position of last occurrence)Extracting Substrings
slice(start, end) — Extract Part of a String
let text = "JavaScript Tutorial";
console.log(text.slice(0, 10)); // JavaScript
console.log(text.slice(11)); // Tutorial
console.log(text.slice(-8)); // Tutorial (negative index from end)substring(start, end) — Similar to slice but No Negative Index
let text = "Hello World";
console.log(text.substring(6, 11)); // WorldReplacing Content
replace() — Replace First Occurrence
let text = "I love cats. Cats are cute.";
console.log(text.replace("cats", "dogs")); // I love dogs. Cats are cute.replaceAll() — Replace All Occurrences
let text = "apple, apple, apple";
console.log(text.replaceAll("apple", "mango")); // mango, mango, mangoSplitting a String
split() — Convert String to Array
let fruits = "Apple,Banana,Mango,Orange";
let fruitArray = fruits.split(",");
console.log(fruitArray); // ["Apple", "Banana", "Mango", "Orange"]
// Split by space
let sentence = "Hello World JavaScript";
console.log(sentence.split(" ")); // ["Hello", "World", "JavaScript"]
// Split each character
console.log("abc".split("")); // ["a", "b", "c"]Padding Strings
padStart() and padEnd() — Add Padding to Reach a Target Length
// Useful for formatting invoice numbers, times, etc.
let id = "42";
console.log(id.padStart(5, "0")); // "00042"
let amount = "500";
console.log(amount.padEnd(8, ".")); // "500....."Repeating Strings
let star = "*";
console.log(star.repeat(5)); // *****String to Number and Back
// String to Number
let strNum = "42";
console.log(Number(strNum)); // 42
console.log(parseInt(strNum)); // 42
// Number to String
let num = 100;
console.log(num.toString()); // "100"
console.log(String(num)); // "100"Escape Characters
Special characters inside strings are represented using backslash \ escape sequences.
| Escape | Meaning |
|---|---|
| \n | New line |
| \t | Tab |
| \' | Single quote |
| \" | Double quote |
| \\ | Backslash |
let message = "He said, \"Hello!\"";
console.log(message); // He said, "Hello!"
let lines = "Line 1\nLine 2\nLine 3";
console.log(lines);
// Line 1
// Line 2
// Line 3Practical Example — Format a User Profile
let rawName = " ananya sharma ";
let email = "ANANYA@EXAMPLE.COM";
let phone = "9876543210";
let cleanName = rawName.trim();
let formattedName = cleanName
.split(" ")
.map(word => word[0].toUpperCase() + word.slice(1).toLowerCase())
.join(" ");
let formattedEmail = email.toLowerCase();
let formattedPhone = phone.slice(0, 5) + "-" + phone.slice(5);
console.log("Name:", formattedName); // Ananya Sharma
console.log("Email:", formattedEmail); // ananya@example.com
console.log("Phone:", formattedPhone); // 98765-43210Key Points to Remember
- Strings can use single quotes, double quotes, or backticks
- Template literals (backticks) allow embedding variables with
${ } - Use
trim()to clean up whitespace from user inputs toUpperCase()andtoLowerCase()change letter casingincludes(),startsWith(), andendsWith()search within stringsslice()extracts a portion of a string without modifying the originalreplace()andreplaceAll()substitute text within stringssplit()converts a string into an array- Strings are immutable — methods always return a new string, never modify the original
