What the replace method does
The replace method finds text inside a string and swaps it out for different text. When you call replace on a string, you give it two pieces of information: the text you want to find and the text you want to put in its place. The method returns a new string with that swap made — it does not change the original string.
In most programming languages, replace works the same basic way, though the exact syntax changes. The method searches from the beginning of the string, finds the first match, replaces it, and stops. If you want to replace every occurrence instead of just the first one, you use a different method or add a flag.
Key Takeaways
- The replace method finds the first occurrence of a substring and returns a new string with that text swapped out — the original string stays unchanged.
- In Python, use string.replace(old, new); in JavaScript, use string.replace(searchValue, newValue); in Java, use string.replace(oldChar, newChar).
- To replace all occurrences instead of just the first, use replaceAll() in Python and Java, or add the global flag in JavaScript regex.
- Replace is case-sensitive by default, so "Hello" and "hello" are treated as different text.
- The method works with plain text or with regex patterns, depending on the language and which version you use.
Replace in Python
In Python, the syntax is string.replace(old, new). You call the method on the string itself, pass the text to find as the first argument, and the replacement text as the second. Here is a basic example:
message = "The cat sat on the mat" new_message = message.replace("cat", "dog") print(new_message)
The output is "The dog sat on the mat". Notice that the original message variable is unchanged — replace returns a new string, so you have to store it in a variable or use it right away.
By default, replace only changes the first match. If your string is "cat cat cat" and you call replace("cat", "dog"), you get "dog cat cat". To replace every occurrence, use replaceAll() instead, or pass a third argument to replace: string.replace(old, new, count), where count is how many replacements to make. If you leave count out or set it to -1, all occurrences are replaced.
Replace in JavaScript
In JavaScript, the syntax is string.replace(searchValue, newValue). Like Python, it returns a new string and only replaces the first match by default.
let message = "The cat sat on the mat"; let newMessage = message.replace("cat", "dog"); console.log(newMessage);
The output is "The dog sat on the mat". To replace all occurrences, use replaceAll() instead, which is available in modern JavaScript:
let newMessage = message.replaceAll("cat", "dog"); console.log(newMessage);
This gives you "The dog sat on the dog". Alternatively, you can use the replace() method with a regular expression and the global flag g: message.replace(/cat/g, "dog"). The regex approach is more powerful if you need to find patterns rather than exact text.
Replace in Java
In Java, there are two main replace methods. The replace(char oldChar, char newChar) method works on single characters, while replace(CharSequence target, CharSequence replacement) works on strings. Both return a new string and only replace the first match.
String message = "The cat sat on the mat"; String newMessage = message.replace("cat", "dog"); System.out.println(newMessage);
The output is "The dog sat on the mat". To replace all occurrences, use replaceAll(String regex, String replacement), which takes a regular expression as the first argument:
String newMessage = message.replaceAll("cat", "dog"); System.out.println(newMessage);
This gives you "The dog sat on the dog". Be careful with replaceAll() — if your search text contains special regex characters like ., *, or ?, you need to escape them with a backslash, or the method will treat them as regex patterns instead of literal text.
Case sensitivity and special characters
Replace is case-sensitive in all major languages. If you search for "Cat" in a string that contains "cat", the method will not find a match. To do a case-insensitive search, you have a few options: convert the string to all lowercase or uppercase before searching, use a regex pattern with the case-insensitive flag, or use a language-specific method if one exists.
Special characters like spaces, punctuation, and line breaks are treated as literal text by the basic replace method. If you want to find or replace a newline character, use \n in the search string. Tabs are \t. In regex-based replace methods, special characters have different meanings, so escape them if you want to match them literally.
Using regex with replace
Regular expressions let you search for patterns instead of exact text. For example, you can find any digit, any whitespace, or any word that starts with a capital letter. The syntax varies by language, but the idea is the same: you write a pattern, and replace finds all text that matches that pattern.
In JavaScript, message.replace(/\d+/g, "X") replaces all sequences of digits with "X". The \d means "any digit" and the + means "one or more". The g flag means "global" — replace all matches, not just the first.
In Python, re.sub(r"\d+", "X", message) does the same thing. You need to import the re module first. In Java, message.replaceAll("\\d+", "X") works the same way — note that Java requires double backslashes in string literals.
Learning regex takes time, but it is powerful for complex replacements. Start with straightforward patterns and test them before using them in production code.
Common mistakes and how to avoid them
The most common mistake is forgetting that replace returns a new string. If you write message.replace("cat", "dog") and do not store the result, the original string is unchanged. Always assign the result to a variable: message = message.replace("cat", "dog").
Another mistake is using replace when you meant replaceAll. If your code only changes the first match and you expected all matches to change, switch to the replaceAll method. Be careful with replaceAll and regex — if your search text contains regex special characters and you did not escape them, the method will treat them as patterns and may fail or produce unexpected results.
A third mistake is assuming replace is case-insensitive. It is not. If you need to match "Hello", "hello", and "HELLO" all at once, convert the string to one case before searching, or use a regex pattern with the case-insensitive flag.
Frequently Asked Questions
Does replace change the original string?
No. Replace returns a new string with the replacement made. The original string stays the same. If you want to keep the result, you must store it in a variable or use it when ready.
How do I replace all occurrences, not just the first one?
Use replaceAll() instead of replace(). In Python, you can also pass a third argument: string.replace(old, new, -1). In JavaScript, use replaceAll() or use replace() with a regex and the global flag g.
Can I replace text without caring about uppercase or lowercase?
Yes, but the method depends on your language. In JavaScript, use a regex with the case-insensitive flag: message.replace(/cat/i, "dog"). In Python, convert the string to lowercase first, then replace. In Java, use a regex with the case-insensitive flag in replaceAll().
What if the text I want to find contains special characters like a period or asterisk?
If you are using a regex-based replace method, escape the special character with a backslash. For example, to find a literal period, use \. instead of just .. If you are using a plain text replace method, special characters are treated as literal text automatically, so no escaping is needed.
Can I use replace to remove text?
Yes. Replace the text with an empty string. For example, message.replace("cat", "") removes the first occurrence of "cat". Use replaceAll("cat", "") to remove all occurrences.