You can replace any word or characters you want in JavaScript using the replace() method. One of the powerful features of the replace method is that not only can it replace matched strings but can also replace string patterns.
Here’s an example of how it can replace strings when it matches the substring:
const text = 'Hi from NightProgrammer! Hi from here!'
const result = text.replace('Hi', 'Hello')
console.log(result)
Code language: JavaScript (javascript)
The result would look like this:
Hello from NightProgrammer! Hi from here!
Code language: JavaScript (javascript)
You’d notice that only that the first ‘Hi’ in the sentence got replaced with ‘Hello’ but the second ‘Hi’ remains as such. This is because when we pass a substring to the replace() method, it only replaces the first occurrence of that substring.
You can, however, use a regular expression to replace all the substrings instead:
const resultAll = text.replace(/Hi/g, 'Hello')
console.log(resultAll)
Code language: JavaScript (javascript)
Now the output would change to:
Hello from NightProgrammer! Hello from here!
Code language: JavaScript (javascript)
If you have any questions or suggestions, let me know in the comments below!