0

My code is:

function fms(e) {
  eq = e
  eq = eq.replace('f(', '<em>f</em>(')
  eq = eq.replace(' / ', ' &#247; ')
  eq = eq.replace('{', '<sup>')
  eq = eq.replace('}', '</sup>')
  return eq
}
a = fms('x{y} x{y}')
console.log(a)

And it is supposed to add sup around whatever is in the {}, but: my a variable only has around the first pair, and the second left unchanged:

x<sup>y</sup> x{y}

I am puzzled. If you know why, make sure to let me know!

Harshit Rastogi
  • 1,996
  • 1
  • 10
  • 19
jwu
  • 11
  • 10

1 Answers1

1

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(' / ', ' &#247; ')
  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, ' &#247; ')
  eq = eq.replace(/{/g, '<sup>')
  eq = eq.replace(/}/g, '</sup>')
  return eq
}
a = fms('x{y} x{y}');
console.log(a);
Nitheesh
  • 19,238
  • 3
  • 22
  • 49