Use replaceAll
instead of replace
since you are using a string to be replaced by another sting.
String.prototype.replace()
The replace()
method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string
or a RegExp
, and the replacement can be a string
or a function
to be called for each match. If pattern is a string, only the first occurrence will be replaced.
Reference
function fms(e) {
eq = e
eq = eq.replaceAll('f(', '<em>f</em>(')
eq = eq.replaceAll(' / ', ' ÷ ')
eq = eq.replaceAll('{', '<sup>')
eq = eq.replaceAll('}', '</sup>')
return eq
}
a = fms('x{y} x{y}');
console.log(a)
How to make String.replace
replace all the occurances?
You can replace all the occurances of a sring using replace
itself, if we make use of a regex
instead of the string.
Working Example
function fms(e) {
eq = e;
eq = eq.replace(/f\(/g, '<em>f</em>(')
eq = eq.replace(/\//g, ' ÷ ')
eq = eq.replace(/{/g, '<sup>')
eq = eq.replace(/}/g, '</sup>')
return eq
}
a = fms('x{y} x{y}');
console.log(a);