What is a String
A string is a sequence of characters used to represent text. In JavaScript, strings are immutable, which means once a string is created, it cannot be changed. Any operation on a string creates a new string instead of modifying the original.
Example:
let str = "Hello";
str[0] = "J"; // Trying to change the first character (Immutable)
console.log(str); // Output: "Hello"
let newStr = str.concat(" World");
console.log(str); // Output: Hello
console.log(newStr); // Output: Hello WorldIs It Immutable
In Above code we are trying to change str[0] = "J";, but it will not change. That's why it is immutable.
Note : In JavaScript, square brackets [] are used to access elements in arrays or properties in objects. When working with strings, square brackets are used to access individual characters at a specific index.
Example:let str = "Hello";console.log(str[0]); // "H"console.log(str[1]); // "e"
Important Points:
- Zero-Based Indexing: Strings are indexed starting from 0. So,
str[0]gives you the first character,str[1]gives the second, and so on. - Strings are Immutable: You cannot modify string characters directly using
[]. For example,str[0] = "h";will not work as strings are immutable. - Alternative Access: You can also use the
.charAt()method to access characters. For example,str.charAt(0);will return "H".
String Methods with Examples
Here are some commonly used string methods with examples:
length: Returns the length of the string, i.e., the number of characters in the string, including spaces.// Syntax: let length = str.length; let str = "Hello"; console.log(str.length); // Output: 5charAt(): Returns the character at a specified index in the string. If the index is out of range, it returns an empty string.// Syntax: let char = str.charAt(index); let str = "Hello"; console.log(str.charAt(1)); // Output: e console.log(str.charAt(5)); // Output: "" (empty string)slice(): Extracts a section of a string and returns it as a new string without modifying the original string. It accepts **positive or negative indices**: a negative index counts from the end of the string.// Syntax: let slicedStr = str.slice(startIndex, endIndex); let str = "Hello World"; console.log(str.slice(0, 5)); // Output: Hello console.log(str.slice(6)); // Output: World console.log(str.slice(-5)); // Output: World console.log(str.slice(-11, -6)); // Output: Hellosubstring(): Similar toslice(), but does not support negative indices. Extracts a part of the string between two indices.// Syntax: let substr = str.substring(startIndex, endIndex); let str = "Hello World"; console.log(str.substring(0, 5)); // Output: Hello console.log(str.substring(6)); // Output: Worldconcat(): Combines two or more strings into a new string.// Syntax: let newStr = str1.concat(str2, str3, ...); let str1 = "Hello"; let str2 = "World"; console.log(str1.concat(" ", str2)); // Output: Hello WorldindexOf(): Returns the index of the first occurrence of a specified value in the string. Returns-1if the value is not found.// Syntax: let index = str.indexOf(searchValue); let str = "Hello World"; console.log(str.indexOf("World")); // Output: 6 console.log(str.indexOf("world")); // Output: -1replace(): Replaces the first occurrence of a specified value in the string with another value. For global replacements, use a regular expression with thegflag.// Syntax: let newStr = str.replace(searchValue, newValue); let str = "Hello World"; console.log(str.replace("World", "JavaScript")); // Output: Hello JavaScript // Global replacement: let str2 = "Hello World World"; console.log(str2.replace(/World/g, "JavaScript")); // Output: Hello JavaScript JavaScripttoUpperCase()&toLowerCase(): Converts the string to uppercase or lowercase, respectively.// Syntax: let upperCaseStr = str.toUpperCase(); let lowerCaseStr = str.toLowerCase(); let str = "Hello"; console.log(str.toUpperCase()); // Output: "HELLO" console.log(str.toLowerCase()); // Output: "hello"trim(): Removes whitespace from both ends of the string. It does not change the original string but returns a new trimmed string.// Syntax: let trimmedStr = str.trim(); let str = " Hello "; console.log(str.trim()); // Output: "Hello"includes(): Checks if a string contains a specified substring. It returns a boolean value (`true` or `false`).// Syntax: let result = str.includes(substring); let str = "Hello World"; console.log(str.includes("World")); // Output: true console.log(str.includes("world")); // Output: false (case-sensitive)split(): Splits a string into an array of substrings based on a specified delimiter. If no delimiter is specified, it returns the entire string as a single array element.// Syntax: let resultArray = str.split(delimiter); let str = "Hello,World"; console.log(str.split(",")); // Output: ["Hello", "World"] let str2 = "JavaScript"; console.log(str2.split("")); // Output: ["J", "a", "v", "a", "S", "c", "r", "i", "p", "t"]startsWith()&endsWith(): Check if a string starts or ends with a specified substring. Both return boolean values.// Syntax: let startsWithResult = str.startsWith(searchString, position); let endsWithResult = str.endsWith(searchString, length); let str = "Hello World"; // startsWith() examples console.log(str.startsWith("Hello")); // true console.log(str.startsWith("World")); // false console.log(str.startsWith("World", 6)); // true (starts checking from index 6) // endsWith() examples console.log(str.endsWith("World")); // true console.log(str.endsWith("Hello")); // false console.log(str.endsWith("Hello", 5)); // true (checks if the first 5 characters end with "Hello")repeat(): Returns a new string with the original string repeated a specified number of times.// Syntax: let repeatedStr = str.repeat(count); let str = "Hello "; console.log(str.repeat(3)); // Output: "Hello Hello Hello " console.log("Ha".repeat(5)); // Output: "HaHaHaHaHa"padStart()&padEnd(): Pad the beginning or end of a string with a specified character to reach a desired length.// Syntax: let paddedStart = str.padStart(targetLength, padString); let paddedEnd = str.padEnd(targetLength, padString); let str = "5"; console.log(str.padStart(3, "0")); // Output: "005" console.log(str.padEnd(3, "*")); // Output: "5**" let name = "John"; console.log(name.padStart(10, " ")); // Output: " John" console.log(name.padEnd(10, "-")); // Output: "John------"replaceAll(): Replaces all occurrences of a specified value in the string with another value (ES2021 feature).// Syntax: let newStr = str.replaceAll(searchValue, replaceValue); let str = "Hello World World"; console.log(str.replaceAll("World", "JavaScript")); // Output: "Hello JavaScript JavaScript" // Note: replaceAll() is more convenient than replace() with regex let str2 = "apple,banana,apple,orange"; console.log(str2.replaceAll("apple", "mango")); // Output: "mango,banana,mango,orange"trimStart()&trimEnd(): Remove whitespace from the beginning or end of a string (ES2019 features).// Syntax: let trimmedStart = str.trimStart(); let trimmedEnd = str.trimEnd(); let str = " Hello World "; console.log(str.trimStart()); // Output: "Hello World " console.log(str.trimEnd()); // Output: " Hello World" // Alias methods (older browsers) console.log(str.trimLeft()); // Same as trimStart() console.log(str.trimRight()); // Same as trimEnd()
Template Literals
Template literals are enclosed by backticks (``) and allow:
- String interpolation using
${expression}. - Multi-line strings without needing escape characters.
Example:
let name = "Prakash";
let greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, Prakash!Note : We will learn Template literals in details later.
String Best Practices
- Use template literals for string interpolation instead of concatenation
- Use
includes()instead ofindexOf() !== -1for better readability - Use
startsWith()andendsWith()instead ofindexOf() === 0 - Use
replaceAll()instead of regex with global flag for simple replacements - Use
padStart()andpadEnd()for formatting numbers and aligning text - Use
trimStart()andtrimEnd()instead oftrim()when you only need to remove whitespace from one end
Difference Between "", '', and ``
Strings in JavaScript can be created using double quotes (""), single quotes (''), or backticks (``):
| Type | Description | Example |
|---|---|---|
Double Quotes ("") | Commonly used for strings. Escape characters (e.g., \) are needed if double quotes are included within the string. You can also use single quotes inside double quotes without escaping. | let str = "He said, \\"Hello!\\""; |
Single Quotes ('') | Similar to double quotes. Escape characters are needed if single quotes are included within the string. You can also use double quotes inside single quotes without escaping. | let str = 'It\\'s a sunny day'; |
Backticks (``) | Used for template literals. Supports string interpolation (e.g., embedding variables) and multi-line strings. | let name = "Alice";
let str = `Hello, ${name}`;
console.log(str); // Output: Hello, Alice
let multiLineStr = `Line 1 <br />Line 2`;
console.log(multiLineStr); // Output: Line 1 Line 2 |
Key Takeaways
Strings are a fundamental part of JavaScript. Understanding their methods and features can greatly enhance your ability to manipulate text and build dynamic applications.