How to Replace Only the First Occurrence of a Character in a String in JavaScript
Replacing a substring is a fundamental string manipulation task. While you often want to replace all occurrences of a character, a common requirement is to replace only the first one you find. The standard String.prototype.replace() method is perfectly designed for this, as its default behavior is to operate only on the first match.
This guide will teach you the simple and direct way to replace the first occurrence of a character or substring using replace(). We will also clarify how this differs from replacing all occurrences and how to perform a case-insensitive replacement.
The Core Method: String.prototype.replace()
The replace() method is the built-in JavaScript tool for finding a substring and replacing it with a new one. When you provide a string as the first argument, it will find and replace only the first match.
Problem: you want to replace only the first hyphen (-) in an ID string with a colon (:).
// Problem: How to replace only the first hyphen?
let id = 'user-123-456';
Solution:
let id = 'user-123-456';
// The replace() method with a string argument only affects the first match.
let newId = id.replace('-', ':');
console.log(newId);
Output:
user:123-456
This is the most concise and readable way to solve the problem.
How replace() Works by Default
string.replace(searchValue, newValue)
where:
searchValue: This can be a string or a regular expression.- When
searchValueis a string,replace()finds the first occurrence of that exact string and replaces it. It then stops. - When
searchValueis a regular expression without the global (g) flag, it also finds the first match and then stops.
Important: Strings are immutable in JavaScript. The replace() method does not change the original string; it returns a new string with the modification.
Replacing the First Occurrence (Case-Insensitive)
The standard replace('find', 'replace') is case-sensitive. To perform a case-insensitive replacement, you must use a regular expression with the i (ignore case) flag.
Problem: you want to replace the first "apple" (regardless of its case) with "orange".
let text = 'This is an Apple. I like apples.';
Solution:
let text = 'This is an Apple. I like apples.';
// The regex /apple/i matches the first "apple", ignoring its case.
// Note: There is no 'g' (global) flag.
let newText = text.replace(/apple/i, 'orange');
console.log(newText);
Output:
This is an orange. I like apples.
The replace() method found "Apple" as the first match and replaced it, leaving the second "apples" untouched.
Comparison: First Occurrence vs. All Occurrences
It's useful to see the difference between replacing the first occurrence and replacing all of them.
let str = 'a-b-c-d';
// Replace only the FIRST hyphen
let replaceFirst = str.replace('-', '_');
console.log(replaceFirst); // Output: a_b-c-d
// Replace ALL hyphens
let replaceAll = str.replaceAll('-', '_');
console.log(replaceAll); // Output: a_b_c_d
// You can also replace all with a global regex
let replaceAllWithRegex = str.replace(/-/g, '_');
console.log(replaceAllWithRegex); // Output: a_b_c_d
Conclusion
Replacing only the first occurrence of a character or substring in JavaScript is simple and direct.
- The recommended best practice is to use the
string.replace('find', 'replace')method, passing a string as the first argument. This is the method's default behavior. - For a case-insensitive replacement of the first occurrence, you must use a regular expression with the
iflag:string.replace(/find/i, 'replace'). - If you need to replace all occurrences, use the more explicit
string.replaceAll()method instead.