Search code examples
javascriptmathjax

How to replace multiple dollar ($) signs by pound signs in a Javascript MathJax text string?


In the character sequence:- $$ \sin \theta $$ I want to replace every $ by a £.


(EDIT: I have since learned that the following approach is overkill, please ignore it. I have added an answer that relates some key learning points. But kudos to Mister Jojo for giving the answser to the original question).


I have looked at the answers to this question:- better-way-to-escape-dollar-signs-in-the-string-used-by-string-prot.

I have tried to apply the answer of Leonid:-

var str = ..., reg = ...;
function replaceString(replaceValue) {
  return str.replace(reg, function () { return replaceValue });
}

This is my interpretation:-

var str = "$$ \sin \theta $$";
//var reg = "/\$/g" ;// TIL: reg is a regular expression so doesn't need "".
var reg = /\$/g ; //... I tried varying the number of $ and/or backslashes,` without success so far.
var replaceValue = "£";
var output = replaceString( replaceValue ); 

//-----------------------------------------------

function replaceString( replaceValue ) 
{
  return str.replace ( reg, function () { return replaceValue });
}

//-----------------------------------------------

// desired output =  "££  \sin \theta ££"
// actual output  =  "$$  sin \theta $$".

It isn't working.


Solution

  • simply use replaceAll() method

    let s1 = "$$  \sin \theta $$"
      , s2 = s1.replaceAll('$','£')
      ;
    console.log ( s2 )