String Manipulation in JavaScript
String manipulation is a core aspect of working with text in JavaScript. JavaScript provides a rich set of built-in methods and techniques for handling and transforming strings.
1. Creating Strings
Strings in JavaScript can be created using single quotes ('
), double quotes ("
), or backticks (`
for template literals).
Example:
const single = 'Hello';
const double = "World";
const template = `Hello, ${double}!`; // Using template literals
console.log(template); // Output: Hello, World!
2. Common String Methods
A. Finding the Length of a String
The .length
property returns the number of characters in a string.
const text = "JavaScript";
console.log(text.length); // Output: 10
B. Accessing Characters
You can access individual characters using bracket notation or the .charAt()
method.
const str = "Hello";
console.log(str[0]); // Output: H
console.log(str.charAt(1)); // Output: e
C. Changing Case
-
.toUpperCase()
converts a string to uppercase. -
.toLowerCase()
converts a string to lowercase.
const text = "JavaScript";
console.log(text.toUpperCase()); // Output: JAVASCRIPT
console.log(text.toLowerCase()); // Output: javascript
D. Searching for Substrings
-
.indexOf()
returns the first index of a substring or-1
if not found. -
.lastIndexOf()
searches from the end of the string.
const text = "JavaScript is awesome!";
console.log(text.indexOf("is")); // Output: 11
console.log(text.lastIndexOf("a")); // Output: 3
E. Checking for Substrings
-
.includes()
checks if a substring exists (returnstrue
orfalse
). -
.startsWith()
checks if a string starts with a specific substring. -
.endsWith()
checks if a string ends with a specific substring.
const text = "Hello, world!";
console.log(text.includes("world")); // Output: true
console.log(text.startsWith("Hello")); // Output: true
console.log(text.endsWith("!")); // Output: true
F. Extracting Substrings
-
.slice(start, end)
extracts part of a string. -
.substring(start, end)
works similarly to.slice
but doesn't accept negative indices. -
.substr(start, length)
extracts a substring of a specified length.
const text = "JavaScript";
console.log(text.slice(0, 4)); // Output: Java
console.log(text.substring(4, 10)); // Output: Script
console.log(text.substr(4, 6)); // Output: Script
G. Splitting Strings
The .split(delimiter)
method splits a string into an array of substrings.
const text = "apple,banana,cherry";
const fruits = text.split(",");
console.log(fruits); // Output: ["apple", "banana", "cherry"]
H. Replacing Substrings
-
.replace(search, replacement)
replaces the first occurrence. -
.replaceAll(search, replacement)
replaces all occurrences.
const text = "I love cats. Cats are great!";
console.log(text.replace("cats", "dogs")); // Output: I love dogs. Cats are great!
console.log(text.replaceAll("Cats", "Dogs")); // Output: I love cats. Dogs are great!
I. Removing Whitespace
-
.trim()
removes whitespace from both ends of a string. -
.trimStart()
and.trimEnd()
remove whitespace from the start or end.
const text = " Hello, world! ";
console.log(text.trim()); // Output: Hello, world!
3. Advanced String Manipulation
A. Reversing a String
You can reverse a string by converting it to an array, reversing the array, and joining it back into a string.
const text = "Hello";
const reversed = text.split("").reverse().join("");
console.log(reversed); // Output: olleH
B. Repeating Strings
The .repeat(count)
method repeats a string multiple times.
const text = "Ha";
console.log(text.repeat(3)); // Output: HaHaHa
C. Padding Strings
-
.padStart(targetLength, padString)
pads the start of a string. -
.padEnd(targetLength, padString)
pads the end of a string.
const text = "5";
console.log(text.padStart(3, "0")); // Output: 005
console.log(text.padEnd(3, "0")); // Output: 500
4. Template Literals
Template literals provide a more readable and concise way to create dynamic strings.
const name = "Alice";
const age = 25;
console.log(`My name is ${name}, and I am ${age} years old.`);
// Output: My name is Alice, and I am 25 years old.
5. Summary
- String manipulation is essential for processing and transforming text data in JavaScript.
- JavaScript provides numerous methods for searching, extracting, transforming, and formatting strings.
- Advanced features like template literals, string reversal, and padding make JavaScript powerful for text-based operations.
By mastering these techniques, you'll be well-equipped to handle complex text operations in your JavaScript applications.
Hi, I'm Abhay Singh Kathayat!
I am a full-stack developer with expertise in both front-end and back-end technologies. I work with a variety of programming languages and frameworks to build efficient, scalable, and user-friendly applications.
Feel free to reach out to me at my business email: kaashshorts28@gmail.com.
Top comments (0)