Open In App

What is jQuery's Equivalent of str_replace in JavaScript?

Last Updated : 22 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, the equivalent of PHP’s str_replace is the replace method of strings. While jQuery doesn't offer a direct str_replace equivalent, JavaScript’s replace and replaceAll methods can be used effectively.

1. Replace a Single Instance with replace

  • This method replaces the first occurrence of a substring.
  • replace("world", "JavaScript") replaces the first occurrence of "world" with "JavaScript."
  • Works for single, non-repeated replacements.
JavaScript
const original = "Hello, world!";
const result = original.replace("world", "JavaScript");
console.log(result);

Output
Hello, JavaScript!

2. Replace All Instances with replaceAll

  • For multiple replacements, use replaceAll (introduced in ES2021).
  • replaceAll("world", "universe") replaces all occurrences of "world."
  • This method is straightforward for global replacements without regular expressions.
JavaScript
const original = "Welcome to the world of JavaScript. Explore the world!";
const result = original.replaceAll("world", "universe");
console.log(result); 

Output
Welcome to the universe of JavaScript. Explore the universe!

3. Using Regular Expressions for Global Replacement

  • For broader compatibility, use replace with a regular expression.
  • /world/g is a regular expression to match all occurrences of "world."
  • The g flag ensures all matches are replaced.
JavaScript
const original = "The world is vast. The world is beautiful.";
const result = original.replace(/world/g, "universe");
console.log(result); 

Output
The universe is vast. The universe is beautiful.

Next Article

Similar Reads