Overview & Purpose
Returns a new string with the first match replaced by a replacement string.
Topic Definition
replace() is the exact operation explained on this reference page. In JavaScript, the important details are the receiver value, accepted arguments, callback behavior if any, returned value, and whether the original data changes. String replace() should be learned as a practical API: first read the syntax, then run the basic example, then check the output, then confirm mutation behavior. This prevents the most common method-reference mistakes, especially when arrays, strings, objects, dates, Math utilities, promises, or browser APIs look similar but return different results.
Why It Matters
Use replace() when its return value and side-effect behavior match your task. The method gives your code a standard vocabulary, reduces custom loops or manual parsing, and makes code reviews easier because other JavaScript developers already know the expected behavior. It is especially useful when you need predictable data transformation, lookup, formatting, async handling, or value calculation.
Syntax Guide
string.replace(searchValue, replaceValue)- searchValue (required) — string to find (only first occurrence), or a RegExp.
- replaceValue (required) — replacement string, or a function(match) => replacement.
A new string with the first match replaced. Original string unchanged. Mutation behavior: No — returns a new string.
Returns a new string with the first match replaced by a replacement string. Related APIs: replaceAll() — replaces ALL occurrences. split().join() — older all-replace pattern. match() — for extraction without replacement.
Runnable Code Examples
Example 1: String replace() syntax
Returns a new string with the first match replaced by a replacement string.
const message = "Hello World! Hello JavaScript!";
// Replace first occurrence only
console.log(message.replace("Hello", "Hi"));
// Using regex with g flag for ALL occurrences
console.log(message.replace(/Hello/g, "Hi"));
// Function replacement
const result = "price: 1000".replace(/d+/, (match) => parseInt(match) * 1.18);
console.log(result);A new string with the first match replaced. Original string unchanged.
Example 2: Real-world String replace() usage
replace() with regex is powerful for sanitization, formatting, and transformation. $1, $2 in replacement string refer to captured groups. Function replacement enables computed replacements.
// Sanitize user input — remove HTML tags
function stripHTML(html) {
return html.replace(/<[^>]*>/g, "");
}
// Format phone number
function formatPhone(phone) {
const digits = phone.replace(/D/g, ""); // Remove non-digits
return digits.replace(/(d{5})(d{5})/, "$1 $2");
}
// URL slug generator
function createSlug(title) {
return title
.toLowerCase()
.replace(/[^a-z0-9 ]/g, "") // Remove special chars
.replace(/s+/g, "-") // Spaces to hyphens
.replace(/^-|-$/g, ""); // Remove leading/trailing hyphens
}
console.log(stripHTML("<h1>Hello <b>World</b></h1>"));
console.log(formatPhone("9876543210"));
console.log(createSlug("JavaScript Arrow Functions — Complete Guide!"));replace() with regex is powerful for sanitization, formatting, and transformation. $1, $2 in replacement string refer to captured groups. Function replacement enables computed replacements.
Example 3: replace() basic example
A focused example showing the core behavior.
const text = "JavaScript Tutorial";
console.log(text.toString());This is the smallest useful example for checking the method behavior.
Real-world Use Cases
- 1
Using replace() while transforming API response data.
- 2
Applying replace() in search, filter, sort, and display logic.
- 3
Using replace() inside form validation or input cleanup.
- 4
Combining replace() with React or Next.js rendering code.
- 5
Explaining replace() in output-based interview questions.
Coding Exercises
Exercise Challenge
Write a minimal example that demonstrates String replace().
Exercise Challenge
Change the input in the String replace() example and predict the output before running it.
Exercise Challenge
Wrap the String replace() example inside a reusable function.
Exercise Challenge
Handle an empty value when using String replace().
Exercise Challenge
Explain String replace() in one comment above your code.
Exercise Challenge
Combine String replace() with a conditional branch.
Exercise Challenge
Create a real-world variable name for String replace().
Exercise Challenge
Add error-safe logging around String replace().
Exercise Challenge
Write one best-practice rule for String replace().
Exercise Challenge
Refactor the String replace() example to use const where reassignment is not needed.
Practice Tasks Checklist
String replace() Quiz Challenges
Quiz Challenge
What is the main purpose of String replace()?
Quiz Challenge
Which question should you ask first when using String replace()?
Quiz Challenge
What should a good String replace() example include?
Quiz Challenge
Why should you test edge cases for String replace()?
Quiz Challenge
Where is String replace() most likely to appear?
Quiz Challenge
What is a strong interview answer for String replace()?
Quiz Challenge
Which debugging step is most useful for String replace()?
Quiz Challenge
What makes String replace() content high quality for learning?
Quiz Challenge
What should you compare when choosing String replace() over a related topic?
Quiz Challenge
What is the best way to master String replace()?
Technical Interview Q&As
1String replace() interview question 1: define the topic in simple language.
Model Answer:
String replace() should be answered with a clear definition, topic-specific syntax, one small example, the expected output, and a practical use case. For this question, focus on the meaning and purpose of the concept.2String replace() interview question 2: show the smallest useful example.
Model Answer:
String replace() should be answered with a clear definition, topic-specific syntax, one small example, the expected output, and a practical use case. For this question, focus on the minimum code needed to demonstrate it.3String replace() interview question 3: predict the output of a sample.
Model Answer:
String replace() should be answered with a clear definition, topic-specific syntax, one small example, the expected output, and a practical use case. For this question, focus on why the output appears in that order.4String replace() interview question 4: explain the most common mistake.
Model Answer:
String replace() should be answered with a clear definition, topic-specific syntax, one small example, the expected output, and a practical use case. For this question, focus on the mistake that usually causes bugs.5String replace() interview question 5: describe a real project use case.
Model Answer:
String replace() should be answered with a clear definition, topic-specific syntax, one small example, the expected output, and a practical use case. For this question, focus on where it appears in production JavaScript.6String replace() interview question 6: compare it with a related JavaScript topic.
Model Answer:
String replace() should be answered with a clear definition, topic-specific syntax, one small example, the expected output, and a practical use case. For this question, focus on how it differs from a nearby concept.7String replace() interview question 7: explain how to debug it.
Model Answer:
String replace() should be answered with a clear definition, topic-specific syntax, one small example, the expected output, and a practical use case. For this question, focus on which console or breakpoint checks reveal the issue.8String replace() interview question 8: mention edge cases.
Model Answer:
String replace() should be answered with a clear definition, topic-specific syntax, one small example, the expected output, and a practical use case. For this question, focus on empty input, wrong type, and boundary behavior.9String replace() interview question 9: state best practices.
Model Answer:
String replace() should be answered with a clear definition, topic-specific syntax, one small example, the expected output, and a practical use case. For this question, focus on readability, safety, and maintainability.10String replace() interview question 10: explain when not to use it.
Model Answer:
String replace() should be answered with a clear definition, topic-specific syntax, one small example, the expected output, and a practical use case. For this question, focus on situations where another approach is clearer.