In JavaScript, replacing all instances of a substring within a string can be achieved using several methods:
1. Using String.prototype.replaceAll():
const originalString = 'Hello world! Hello universe!';
const newString = originalString.replaceAll('Hello', 'Hi');
console.log(newString); // Output: 'Hi world! Hi universe!'
Note: replaceAll() is part of ECMAScript 2021 and may not be supported in all environments. Ensure compatibility or consider using a polyfill if targeting older environments.
2. Using String.prototype.replace() with a Global Regular Expression:
const originalString = 'Hello world! Hello universe!';
const newString = originalString.replace(/Hello/g, 'Hi');
console.log(newString); // Output: 'Hi world! Hi universe!'
In this example, the regular expression /Hello/g matches all occurrences of 'Hello'. The replace() method then replaces each match with 'Hi'.