It looks like the issue is that replace() only replaces the first occurrence in the string, which is causing the issue.
There are two solutions for this issue, which are both very similar.
The first solution is to use String.replaceAll(). This is a new feature introduced in ES2021, which means that it doesn't support old browsers (e.g. Internet Explorer).
To use it, simply use the code below.
const rep = str.replaceAll(f, r); // This line has been modified
document.getElementById("text").innerHTML = rep;
It will use the new method (replaceAll()), which will replace all occurrences of f with r.
The second solution uses a similar, yet older function, called String.replace(). It is the same function that you are using, but we are going to use a different technique.
To replace all occurrences, you need to use RegExp to modify the behaviour.
Use the code below to replace all occurrences with replace().
const rep = str.replace(new RegExp(`${f}`, "g"), r); // This line has been modified
document.getElementById("text").innerHTML = rep;
This uses the new RegExp constructor to create a new RegExp instance. This is because we want to pass in a variable.
The second parameter is where the magic happens. The g means global. This makes the replace() method replace all of the occurrences.
In summary, both of these methods should work. Here are some circumstances of which one you should use.
- Option 1: Use when targeting newer browsers, and are focused on readability.
- Option 2: Use when targeting older browsers.