""
slice
, substr
, replace
, split
, trim
)JavaScript strings come with many built-in methods that help you manipulate text easily. In this section, we'll explore some of the most commonly used string methods:
slice()
substr()
replace()
split()
trim()
Each method serves a specific purpose, such as extracting parts of a string, replacing content, splitting strings into arrays, or removing unwanted whitespace.
slice()
The slice()
method extracts a part of a string and returns it as a new string without modifying the original.
Syntax:
string.slice(startIndex, endIndex)
startIndex
(required): The position where extraction begins (zero-based).endIndex
(optional): The position where extraction ends (not included). If omitted, extracts till the end.Example:
const fullName = "Jane Doe";
// Extract first name (characters from index 0 to 4)
const firstName = fullName.slice(0, 4);
console.log(firstName); // Output: "Jane"
// Extract last name (from index 5 to end)
const lastName = fullName.slice(5);
console.log(lastName); // Output: "Doe"
substr()
The substr()
method extracts a substring starting from a given index and for a specified length.
Syntax:
string.substr(startIndex, length)
startIndex
(required): The starting position.length
(optional): Number of characters to extract.Example:
const url = "https://example.com/page";
// Extract "example"
const domain = url.substr(8, 7);
console.log(domain); // Output: "example"
Note:
substr()
is considered a legacy method and may not be supported in all environments.slice()
orsubstring()
are generally preferred.
replace()
The replace()
method replaces part of a string with another string. It returns a new string without changing the original.
Syntax:
string.replace(searchValue, newValue)
searchValue
: The substring or regular expression to find.newValue
: The string to replace the found substring.Example:
const greeting = "Hello, world!";
const newGreeting = greeting.replace("world", "JavaScript");
console.log(newGreeting); // Output: "Hello, JavaScript!"
By default,
replace()
only changes the first match. To replace all occurrences, use a regular expression with the global flag/g
:
const sentence = "Apples are red. Apples are sweet.";
const updated = sentence.replace(/Apples/g, "Oranges");
console.log(updated);
// Output: "Oranges are red. Oranges are sweet."
split()
The split()
method divides a string into an array of substrings based on a specified separator.
Syntax:
string.split(separator, limit)
separator
: The character(s) or regular expression to split the string on.limit
(optional): Maximum number of splits.Example:
const sentence = "JavaScript,Python,Ruby,Java";
// Split by commas
const languages = sentence.split(",");
console.log(languages); // Output: ["JavaScript", "Python", "Ruby", "Java"]
// Split into maximum 2 parts
const limitedSplit = sentence.split(",", 2);
console.log(limitedSplit); // Output: ["JavaScript", "Python"]
trim()
The trim()
method removes whitespace from both ends of a string but not from inside the string.
Syntax:
string.trim()
Example:
const rawInput = " user@example.com ";
const cleanedInput = rawInput.trim();
console.log(cleanedInput); // Output: "user@example.com"
This is especially useful when processing user input to avoid errors caused by accidental spaces.
Method | Purpose | Key Parameters | Example Use Case |
---|---|---|---|
slice |
Extract substring by start/end | startIndex , endIndex |
Get first or last name |
substr |
Extract substring by start/length | startIndex , length |
Extract part of URL |
replace |
Replace substring | searchValue , newValue |
Replace words in sentences |
split |
Split string into array | separator , limit |
Parse CSV or list strings |
trim |
Remove whitespace around string | None | Clean user input |
By mastering these common string methods, you'll be able to manipulate and transform text efficiently in your JavaScript programs!
Template literals are a modern and powerful way to work with strings in JavaScript. Introduced in ES6, they offer a more readable and flexible alternative to traditional string concatenation.
Template literals are strings enclosed by backticks () instead of single (
') or double (
"`) quotes.
const message = `Hello, world!`;
Using backticks lets you easily:
Instead of this:
const name = "Alice";
const age = 25;
const greeting = "Hello, " + name + "! You are " + age + " years old.";
console.log(greeting);
With template literals, you can write:
const name = "Alice";
const age = 25;
const greeting = `Hello, ${name}! You are ${age} years old.`;
console.log(greeting);
The second version is clearer, shorter, and easier to maintain.
{}
Inside a template literal, anything placed inside ${}
is evaluated as JavaScript code and its result is inserted into the string.
const price = 9.99;
const quantity = 3;
console.log(`Total price: $${price * quantity}`); // Output: Total price: $29.97
You can embed variables, mathematical expressions, function calls, or any valid JavaScript expression.
With traditional strings, to create a multi-line string, you had to use escape characters \n
or concatenate strings:
const poem = "Roses are red,\nViolets are blue,\nJavaScript is fun,\nAnd so are you.";
With template literals, you can simply write:
const poem = `Roses are red,
Violets are blue,
JavaScript is fun,
And so are you.`;
console.log(poem);
This preserves line breaks and formatting exactly as written.
Let's create a small example that generates a personalized greeting and an HTML snippet using template literals.
function createGreeting(name, dayOfWeek) {
return `
<div class="greeting">
<h1>Hello, ${name}!</h1>
<p>Hope you're having a great ${dayOfWeek}.</p>
<p>Today is ${new Date().toLocaleDateString()}.</p>
</div>
`;
}
const userName = "Sam";
const today = "Tuesday";
const greetingHTML = createGreeting(userName, today);
console.log(greetingHTML);
Output:
<div class="greeting">
<h1>Hello, Sam!</h1>
<p>Hope you're having a great Tuesday.</p>
<p>Today is 6/23/2025.</p>
</div>
This HTML string can be injected into a webpage dynamically, demonstrating how template literals make string building easier and cleaner.
${}
to embed variables and expressions inside strings.Try replacing your old concatenation code with template literals — your future self will thank you!
Finding and matching specific parts of a string is a common task in JavaScript. This section introduces simple methods for searching strings as well as an introduction to regular expressions (RegExp) for more powerful pattern matching.
JavaScript provides several built-in methods to search within strings:
Method | Description | Returns |
---|---|---|
indexOf() |
Finds the index of a substring | Index number or -1 if not found |
includes() |
Checks if a substring exists | true or false |
startsWith() |
Checks if string begins with a substring | true or false |
endsWith() |
Checks if string ends with a substring | true or false |
indexOf()
Returns the position of the first occurrence of a substring. If not found, returns -1
.
const text = "JavaScript is fun";
console.log(text.indexOf("Script")); // Output: 4
console.log(text.indexOf("python")); // Output: -1 (not found)
includes()
Returns true
if the substring exists anywhere in the string, otherwise false
.
const email = "user@example.com";
console.log(email.includes("@")); // Output: true
console.log(email.includes("gmail")); // Output: false
startsWith()
and endsWith()
Check if a string starts or ends with a specified substring.
const url = "https://example.com";
console.log(url.startsWith("https")); // true
console.log(url.endsWith(".com")); // true
console.log(url.startsWith("http")); // true
console.log(url.endsWith(".org")); // false
When simple substring searches are not enough, regular expressions provide a flexible way to match complex patterns in strings.
A RegExp is a pattern used to match character combinations.
You create regex patterns with:
const pattern = /pattern/flags;
or
const pattern = new RegExp("pattern", "flags");
const input = "12345";
const digitPattern = /^\d+$/; // ^ = start, \d = digit, + = one or more, $ = end
console.log(digitPattern.test(input)); // true
console.log(digitPattern.test("123a5")); // false
Here is a simple regex to validate a basic email format:
const email = "user@example.com";
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (emailPattern.test(email)) {
console.log("Valid email address.");
} else {
console.log("Invalid email address.");
}
^
and $
mark the start and end of the string.[^\s@]+
means one or more characters that are not whitespace or @
.@
is matched literally.\.
matches the dot before the domain extension.You can also use .match()
to find matches:
const sentence = "I have 2 cats and 3 dogs.";
const numbers = sentence.match(/\d+/g); // Find all numbers
console.log(numbers); // Output: ["2", "3"]
/\d+/g
searches for one or more digits globally (g
flag)..match()
returns an array of matches.Method | Purpose | Returns |
---|---|---|
indexOf() |
Position of substring | Number or -1 |
includes() |
Check if substring exists | Boolean |
startsWith() |
Check prefix of string | Boolean |
endsWith() |
Check suffix of string | Boolean |
RegExp.test() |
Test if string matches pattern | Boolean |
String.match() |
Find matches for regex | Array of matches or null |
For simple substring searches, indexOf
, includes
, startsWith
, and endsWith
are straightforward and efficient. For more advanced pattern matching and validation — such as email formats, phone numbers, or custom rules — regular expressions are an invaluable tool.
With practice, you’ll gain the ability to harness both simple methods and regex to build robust string handling in your JavaScript programs!