JavaScript String Methods
JavaScript provides a variety of built-in methods to manipulate and work with strings. These methods make it easier for developers to transform, search, extract, and format text data. In this lesson, we'll explore the most commonly used string methods that will help you handle text effectively in your web applications.
Introduction to String Methods
In JavaScript, strings are objects that have properties and methods. A method is essentially a function that belongs to an object - in this case, the string. String methods allow you to perform operations like:
- Extracting parts of a string
- Changing the case of characters
- Searching for specific content
- Replacing parts of a string
- And much more!
Let's dive into the most useful string methods with examples.
Basic String Methods
length
Property
While not technically a method, the length
property is crucial for working with strings:
const greeting = "Hello, World!";
console.log(greeting.length); // 13
charAt()
- Character at a Position
Returns the character at a specified position:
const text = "JavaScript";
console.log(text.charAt(0)); // "J"
console.log(text.charAt(4)); // "S"
concat()
- Joining Strings
Combines two or more strings:
const firstName = "John";
const lastName = "Doe";
const fullName = firstName.concat(" ", lastName);
console.log(fullName); // "John Doe"
Note: In modern JavaScript, it's more common to use the +
operator or template literals to concatenate strings:
// Using + operator
const fullName1 = firstName + " " + lastName;
// Using template literals
const fullName2 = `${firstName} ${lastName}`;
Case Modification Methods
toUpperCase()
and toLowerCase()
Change the case of all characters in a string:
const message = "Hello World";
console.log(message.toUpperCase()); // "HELLO WORLD"
console.log(message.toLowerCase()); // "hello world"
Searching and Extraction Methods
indexOf()
and lastIndexOf()
Find the position of a substring within a string:
const sentence = "The quick brown fox jumps over the lazy dog";
console.log(sentence.indexOf("fox")); // 16
console.log(sentence.indexOf("cat")); // -1 (not found)
console.log(sentence.lastIndexOf("the")); // 31
includes()
- Checking Substring Existence
Determines whether a string contains the specified substring:
const email = "[email protected]";
console.log(email.includes("@")); // true
console.log(email.includes("test")); // false
startsWith()
and endsWith()
Check if a string begins or ends with a specific substring:
const filename = "document.pdf";
console.log(filename.startsWith("doc")); // true
console.log(filename.endsWith(".pdf")); // true
console.log(filename.endsWith(".txt")); // false
slice()
, substring()
, and substr()
Extract parts of a string:
const text = "JavaScript is amazing";
// slice(start, end) - extracts from start to end (end not included)
console.log(text.slice(0, 10)); // "JavaScript"
console.log(text.slice(11)); // "is amazing"
console.log(text.slice(-7)); // "amazing"
// substring(start, end) - similar to slice but doesn't accept negative indices
console.log(text.substring(0, 10)); // "JavaScript"
// substr(start, length) - extracts length characters from start
console.log(text.substr(11, 2)); // "is"
Note: substr()
is considered legacy and should be avoided in new code.
Trimming Methods
trim()
, trimStart()
, and trimEnd()
Remove whitespace from strings:
const input = " Hello World! ";
console.log(input.trim()); // "Hello World!"
console.log(input.trimStart()); // "Hello World! "
console.log(input.trimEnd()); // " Hello World!"
String Modification Methods
replace()
and replaceAll()
Replace content within a string:
const message = "Hello world, welcome to the world of JS";
console.log(message.replace("world", "everyone")); // "Hello everyone, welcome to the world of JS"
console.log(message.replaceAll("world", "everyone")); // "Hello everyone, welcome to the everyone of JS"
split()
- Converting String to Array
Splits a string into an array of substrings:
const csvData = "John,Doe,35,Developer";
const dataArray = csvData.split(",");
console.log(dataArray); // ["John", "Doe", "35", "Developer"]
const sentence = "JavaScript is fun to learn";
const words = sentence.split(" ");
console.log(words); // ["JavaScript", "is", "fun", "to", "learn"]
padStart()
and padEnd()
Pad a string to a certain length:
const num = "5";
console.log(num.padStart(3, "0")); // "005"
console.log(num.padEnd(3, "0")); // "500"
Real-World Applications
Example 1: Form Validation
function validateEmail(email) {
// Check if email contains @ and ends with .com, .org, etc.
if (!email.includes("@") || !email.includes(".")) {
return "Invalid email format";
}
// Make sure there's text before @ and between @ and .
const parts = email.split("@");
if (parts.length !== 2 || parts[0].length === 0 || parts[1].length === 0) {
return "Invalid email format";
}
const domainParts = parts[1].split(".");
if (domainParts.length < 2 || domainParts[domainParts.length - 1].length < 2) {
return "Invalid domain format";
}
return "Email validation passed";
}
console.log(validateEmail("[email protected]")); // "Email validation passed"
console.log(validateEmail("invalid-email")); // "Invalid email format"
Example 2: Formatting a URL Slug
function createUrlSlug(title) {
// Convert to lowercase
let slug = title.toLowerCase();
// Replace spaces with hyphens
slug = slug.replaceAll(" ", "-");
// Remove special characters
slug = slug.replace(/[^\w-]/g, "");
return slug;
}
console.log(createUrlSlug("JavaScript String Methods 101!")); // "javascript-string-methods-101"
console.log(createUrlSlug("How to Learn Programming?")); // "how-to-learn-programming"
Example 3: Extracting Information from a String
function parseUserInfo(userString) {
// Format: "name:John Doe;age:30;role:Developer"
const info = {};
const pairs = userString.split(";");
pairs.forEach(pair => {
const [key, value] = pair.split(":");
info[key] = value;
});
return info;
}
const userInfo = parseUserInfo("name:John Doe;age:30;role:Developer");
console.log(userInfo);
// Output: { name: "John Doe", age: "30", role: "Developer" }
Summary
In this lesson, we've explored the most commonly used string methods in JavaScript:
- Basic methods like
charAt()
andconcat()
- Case modification with
toUpperCase()
andtoLowerCase()
- Search methods including
indexOf()
,includes()
,startsWith()
, andendsWith()
- Extraction methods like
slice()
andsubstring()
- Trimming methods:
trim()
,trimStart()
, andtrimEnd()
- Modification methods such as
replace()
,replaceAll()
, andsplit()
- Padding methods:
padStart()
andpadEnd()
These string methods are essential tools for text manipulation in JavaScript and will help you solve a wide range of programming challenges.
Practice Exercises
- Create a function that counts the occurrences of a specific character in a string.
- Write a function that capitalizes the first letter of each word in a sentence.
- Develop a simple password validator that checks for minimum length, uppercase, lowercase, and numbers.
- Create a function that extracts all email addresses from a text.
- Implement a function that reverses each word in a sentence while maintaining the word order.
Additional Resources
Mastering string methods will significantly enhance your capability to work with text data in JavaScript applications. Practice these methods regularly to become proficient in text manipulation.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)