JAVASCRIPT

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.

How to Use String replace() in JavaScript

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

let newString = oldString.replace(substring, newSubstring);

  • oldString: The original string containing the substring.
  • substring: The string to be replaced.
  • newSubstring: The string to replace the old substring.

For more advanced patterns, you can use regular expressions.

let newString = oldString.replace(/pattern/, newSubstring);

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

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.

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

Formatting Strings

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

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.

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

Examples of Using String replace() in JavaScript

Sanitizing User Input

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

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

Updating Text in Files

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

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>"

Customizing Automated Messages

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

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."

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).

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, replaces all occurrences of a substring without needing regular expressions.

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().

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."

Performance Considerations

replace() works efficiently for small strings. For extensive text processing, consider alternative approaches for better performance.

Unicode and International Text

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

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.

Learn JavaScript for Free
Start learning now
button icon
To advance beyond this tutorial and learn JavaScript by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2024 Mimo GmbH