Course

JavaScript Replace: Replacing Text in JavaScript

What is replace() in JavaScript?

The replace() method in JavaScript is a powerful tool for string manipulation. It allows you to replace a substring within a string with another.

The method supports both simple string replacements and advanced replacements using regex (regular expressions).

How to Use String replace() in JavaScript

The replace() method syntax takes two parameters: the substring to be replaced and the new substring.

jsx
let newString = oldString.replace(substring, newSubstring);
  • oldString: The original string containing the substring.
  • substring: The string to be replaced or a regexp pattern.
  • newSubstring: The string to replace the old substring.

For more advanced patterns, you can use regular expressions (regex).

jsx
let newString = oldString.replace(/pattern/, newSubstring);
jsx
let text = "Hello world!"; let newText = text.replace("world", "Mimo"); console.log(newText); // Outputs: "Hello Mimo!"

You can also use string.prototype.replace, which is the built-in method directly tied to JavaScript strings for efficient string manipulation.

How to Replace a Part of a String in JavaScript

The replace() method is useful for a wide range of scenarios:

Correcting User Input

You can use replace() to correct common typos or user input mistakes. For example, it’s a good idea to read the expected format and apply string replacement methods accordingly when correcting inputs:

jsx
let userInput = "Heloo"; let correctedInput = userInput.replace("Heloo", "Hello"); console.log(correctedInput); // Outputs: "Hello"

Using str.replace with Complex Patterns

For more control over replacements, str.replace can combine with custom logic.

jsx
let text = "Numbers: 123, 456, and 789."; let newText = text.replace(/\d+/g, (match) => parseInt(match) * 2); console.log(newText); // Outputs: "Numbers: 246, 912, and 1578."

The replace function allows for complex replacements with callback logic.

jsx
let text = "Numbers: 123, 456, and 789."; let newText = text.replace(/\d+/g, (match) => parseInt(match) * 2); console.log(newText); // Outputs: "Numbers: 246, 912, and 1578."

Formatting Strings

replace() is handy for formatting strings by replacing placeholders with actual values.

jsx
let template = "Dear [name], your balance is [balance]"; let formatted = template.replace("[name]", "Alice").replace("[balance]", "$100"); console.log(formatted); // Outputs: "Dear Alice, your balance is $100"

Processing Logs

Logs often need to be cleaned or standardized. Use replace() to update specific entries.

jsx
let log = "Error: user123 failed login"; let updatedLog = log.replace("user123", "user"); console.log(updatedLog); // Outputs: "Error: user failed login"

Replacing Words in HTML Content

Web developers can use replace() to dynamically update HTML content or modify user-generated data displayed on a webpage.

jsx
let htmlSnippet = "<div>Old Text</div>"; let updatedSnippet = htmlSnippet.replace("Old Text", "New Text"); console.log(updatedSnippet); // Outputs: "<div>New Text</div>"

JavaScript replace() can also modify inline CSS dynamically.

jsx
let styles = "color: red; font-size: 16px;"; let updatedStyles = styles.replace("red", "blue"); console.log(updatedStyles); // Outputs: "color: blue; font-size: 16px;"

Examples of Using String replace() in JavaScript

Sanitizing User Input

Web applications might use replace() to sanitize user inputs and remove potentially harmful characters.

jsx
let userInput = "<script>alert('Hello!');</script>"; let sanitizedInput = userInput.replace("<script>", "").replace("</script>", ""); console.log(sanitizedInput); // Outputs: "alert('Hello!');"

Using Regular Expressions with the g Flag

To replace all occurrences of a substring when using a regular expression, use the global flag (/g). For string literals, use the newer replaceAll() method instead.

jsx
let text = "foo bar foo"; let newText = text.replace(/foo/g, "baz"); console.log(newText); // Outputs: "baz bar baz"
  • The replace() method is used to replace occurrences of a pattern in a string.
  • /foo/g is a regular expression where:
    • foo is the pattern to match.
    • g is the global flag, which ensures that all matches in the string are replaced, not just the first one.

Updating Text in Files

File processing applications often use replace() to update specific text within files.

jsx
let document = "Visit our site at <http://oldsite.com>"; let updatedDocument = document.replace("<http://oldsite.com>", "<http://newsite.com>"); console.log(updatedDocument); // Outputs: "Visit our site at <http://newsite.com>"

Text-processing API calls often require modifying responses.

jsx
fetch("https://api.example.com/data") .then(response => response.text()) .then(text => { let updatedText = text.replace("oldValue", "newValue"); console.log(updatedText); });

Customizing Automated Messages

Customer service applications can use replace() to personalize automated messages.

jsx
let message = "Hello [customer], your order #[order_id] is confirmed."; let customMessage = message.replace("[customer]", "John").replace("[order_id]", "123456"); console.log(customMessage); // Outputs: "Hello John, your order #123456 is confirmed."

You can use chaining to apply multiple replacements efficiently.

jsx
let message = "Hello [customer], your order #[order_id] is confirmed."; let customMessage = message .replace("[customer]", "John") .replace("[order_id]", "123456"); console.log(customMessage); // Outputs: "Hello John, your order #123456 is confirmed."

Returning a Transformed Value

The return value of replace() is always a new string. This means the original string remains unaltered, ensuring safe operations.

jsx
let original = "Learn regex and JavaScript."; let transformed = original.replace("regex", "RegExp"); console.log(transformed); // Outputs: "Learn RegExp and JavaScript." console.log(original); // Outputs: "Learn regex and JavaScript."

The String constructor can be used to apply replace() dynamically.

jsx
let str = new String("Learn regex and JavaScript."); let transformed = str.replace("regex", "RegExp"); console.log(transformed); // Outputs: "Learn RegExp and JavaScript."

Using const and replace()

While working with const strings, you can still use replace() since the method does not mutate the original string but instead returns a new one.

jsx
const greeting = "Hello, user!"; const personalizedGreeting = greeting.replace("user", "Alice"); console.log(personalizedGreeting); // Outputs: "Hello, Alice!"

Learn More About JavaScript String replace()

Replacing All Occurrences of a String in JavaScript

The replace() method only replaces the first occurrence. To replace all occurrences, use a regular expression with the global flag (/g).

jsx
let text = "foo bar foo"; let newText = text.replace(/foo/g, "baz"); console.log(newText); // Outputs: "baz bar baz"

Using replaceAll() in JavaScript

The replaceAll() method, introduced in ES12 (2021), replaces all occurrences of a substring without needing regular expressions.

jsx
let text = "foo bar foo"; let newText = text.replaceAll("foo", "baz"); console.log(newText); // Outputs: "baz bar baz"

Advanced Text Replacement with Regular Expressions

You can replace substrings based on patterns using regular expressions in replace().

jsx
let text = "The rain in SPAIN stays mainly in the plain."; let newText = text.replace(/ain/gi, "AIN"); console.log(newText); // Outputs: "The rAIN in SPAIN stays mAINly in the plAIN."

A capture group can extract and transform parts of a match.

jsx
let text = "Hello John Doe!"; let newText = text.replace(/(\w+) (\w+)/, "$2, $1"); console.log(newText); // Outputs: "Doe, John!"

The /i flag makes replacements case-insensitive.

jsx
let text = "hello WORLD"; let newText = text.replace(/world/i, "JavaScript"); console.log(newText); // Outputs: "hello JavaScript"

Performance Considerations

replace() works efficiently for small to medium-sized strings. For extensive text processing (e.g., strings with millions of characters or when performing many replacements in a loop), consider alternative approaches such as specialized string manipulation libraries or custom algorithms for better performance.

Unicode and International Text

replace() supports Unicode, making it easy to handle international text.

jsx
let text = "こんにちは世界"; let newText = text.replace("世界", "JavaScript"); console.log(newText); // Outputs: "こんにちはJavaScript"

By understanding these techniques and examples, you can effectively use the JavaScript replace() method for various string manipulation tasks.

Looking to dive deeper into JavaScript replace() and other essential JavaScript concepts? Check out our JavaScript course.