JavaScript String Manipulation
Introduction
String manipulation is a fundamental skill in programming. When building applications, you'll frequently need to modify text data - whether it's parsing user input, formatting output, or processing data from external sources.
JavaScript provides a powerful set of built-in methods for string manipulation that allows you to transform, extract, and modify strings in various ways. This guide will walk you through the most common string manipulation techniques and show you practical applications for each.
Basic String Operations
String Concatenation
One of the simplest string operations is concatenation - joining strings together.
// Using the + operator
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;
console.log(fullName); // Output: John Doe
// Using template literals (ES6)
fullName = `${firstName} ${lastName}`;
console.log(fullName); // Output: John Doe
Template literals offer a more readable and flexible way to combine strings, especially when working with multiple variables or multiline strings.
String Length
To find the length of a string, use the length
property:
let message = "Hello, World!";
console.log(message.length); // Output: 13
Extracting String Parts
JavaScript provides several methods to extract portions of strings:
substring()
The substring()
method extracts characters between two indices from a string:
let text = "JavaScript is fun";
// Extract characters from index 0 to 10 (not including 10)
let extract = text.substring(0, 10);
console.log(extract); // Output: JavaScript
slice()
The slice()
method is similar to substring()
but allows negative indices (counting from the end):
let text = "JavaScript is fun";
// Extract characters from index 0 to 10 (not including 10)
let extract1 = text.slice(0, 10);
console.log(extract1); // Output: JavaScript
// Extract the last 3 characters
let extract2 = text.slice(-3);
console.log(extract2); // Output: fun
substr()
The substr()
method extracts a specified number of characters from a string, starting at a specified position:
let text = "JavaScript is fun";
// Extract 10 characters starting from index 0
let extract = text.substr(0, 10);
console.log(extract); // Output: JavaScript
Note: While substr()
is still widely supported, it's considered deprecated. It's better to use substring()
or slice()
for new code.
Modifying Strings
replace()
The replace()
method replaces a specified value with another value in a string:
let text = "I like oranges";
// Replace first occurrence
let newText = text.replace("oranges", "apples");
console.log(newText); // Output: I like apples
// Replace all occurrences using a regular expression with global flag
let repeatedText = "apples and apples";
let replacedText = repeatedText.replace(/apples/g, "oranges");
console.log(replacedText); // Output: oranges and oranges
toUpperCase() and toLowerCase()
These methods convert strings to uppercase or lowercase:
let text = "Hello, World!";
console.log(text.toUpperCase()); // Output: HELLO, WORLD!
console.log(text.toLowerCase()); // Output: hello, world!
trim()
The trim()
method removes whitespace from both ends of a string:
let text = " Hello World! ";
console.log(text.trim()); // Output: Hello World!
// You can also use trimStart() or trimEnd() to remove whitespace
// from just the beginning or end
console.log(text.trimStart()); // Output: "Hello World! "
console.log(text.trimEnd()); // Output: " Hello World!"
Searching Within Strings
indexOf() and lastIndexOf()
These methods return the position of the first or last occurrence of a specified text:
let text = "Please locate where 'locate' occurs!";
// Find the first occurrence of "locate"
console.log(text.indexOf("locate")); // Output: 7
// Find the last occurrence of "locate"
console.log(text.lastIndexOf("locate")); // Output: 21
// If the text is not found, indexOf returns -1
console.log(text.indexOf("banana")); // Output: -1
includes(), startsWith(), endsWith()
Modern JavaScript provides more intuitive methods to check if a string contains, starts with, or ends with specific text:
let text = "Hello world, welcome to the universe.";
// Check if a string contains a specific text
console.log(text.includes("world")); // Output: true
// Check if a string starts with specific text
console.log(text.startsWith("Hello")); // Output: true
// Check if a string ends with specific text
console.log(text.endsWith("universe.")); // Output: true
Split and Join
split()
The split()
method divides a string into an array of substrings based on a separator:
let text = "apple,banana,orange,grape";
// Split by comma
let fruits = text.split(",");
console.log(fruits); // Output: ["apple", "banana", "orange", "grape"]
// Limit the number of splits
let limitedFruits = text.split(",", 2);
console.log(limitedFruits); // Output: ["apple", "banana"]
// Split by characters
let message = "hello";
let chars = message.split("");
console.log(chars); // Output: ["h", "e", "l", "l", "o"]
join()
The join()
method combines array elements into a string:
let fruits = ["apple", "banana", "orange"];
let text = fruits.join(", ");
console.log(text); // Output: "apple, banana, orange"
Practical Examples
Example 1: URL Slug Generator
Create a function that converts a title into a URL-friendly slug:
function createSlug(title) {
return title
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, '') // Remove special characters except spaces and hyphens
.replace(/\s+/g, '-') // Replace spaces with hyphens
.replace(/-+/g, '-'); // Remove consecutive hyphens
}
console.log(createSlug("JavaScript: String Manipulation Guide!"));
// Output: "javascript-string-manipulation-guide"
Example 2: Name Formatter
Format user names for display:
function formatName(firstName, lastName) {
// Capitalize first letter, lowercase the rest
const formattedFirst = firstName.charAt(0).toUpperCase() +
firstName.slice(1).toLowerCase();
const formattedLast = lastName.charAt(0).toUpperCase() +
lastName.slice(1).toLowerCase();
return `${formattedFirst} ${formattedLast}`;
}
console.log(formatName("jOHN", "DOE")); // Output: "John Doe"
Example 3: Email Validator
A simple function to validate email formats:
function isValidEmail(email) {
// Check for @ symbol and at least one dot after it
if (!email.includes('@')) return false;
const parts = email.split('@');
if (parts.length !== 2) return false;
const [username, domain] = parts;
if (username.length === 0) return false;
if (!domain.includes('.')) return false;
return true;
}
console.log(isValidEmail("[email protected]")); // Output: true
console.log(isValidEmail("user@example")); // Output: false
console.log(isValidEmail("user.example.com")); // Output: false
Summary
String manipulation is a core skill in JavaScript programming. We've covered:
- Basic string operations like concatenation and finding length
- Methods to extract parts of strings:
substring()
,slice()
, andsubstr()
- Modifying strings with
replace()
,toUpperCase()
,toLowerCase()
, andtrim()
- Searching within strings using
indexOf()
,includes()
,startsWith()
, andendsWith()
- Splitting strings into arrays and joining arrays into strings
These techniques are essential for text processing tasks in web development, from form validation to data formatting and content management.
Exercises
To practice your string manipulation skills, try these exercises:
- Create a function that reverses a string
- Write a function that counts the occurrences of a specific character in a string
- Create a password strength checker that ensures a password has at least 8 characters, one uppercase letter, one lowercase letter, and one number
- Write a function that extracts all hashtags from a social media post
- Create a function that masks all but the last four digits of a credit card number
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)