-1

I have the following string:

"Write the conjugate of each radical expression.\n\n**(a)** `$2\\sqrt{3} - 4$`\n\n**(b)** `$\\sqrt{3} +\\sqrt{2}$`\n\n**(c)** `$-2\\sqrt{3} - \\sqrt{2}$`\n\n**(d)** `$3\\sqrt{3} + \\sqrt{2} $`\n\n**(e)** `$\\sqrt{2} - \\sqrt{5}$`\n\n**(f)** `$-\\sqrt{5} + 2\\sqrt{2}$`"

And I have the following function to go through a string and replace substrings:

var changeString = function(markdownStr) {
     return markdownStr.replace(/`/g, "").replace("$ ", "$").replace(" $", "$");
};

The result I get is that it replaces some of the conditions (the `), but it didn't work for the last replace condition (" $").

Here is the output:

Write the conjugate of each radical expression. **(a)**$2\sqrt{3} - 4$ **(b)** $\sqrt{3} +\sqrt{2}$ **(c)** $-2\sqrt{3} - \sqrt{2}$ **(d)** $3\sqrt{3} + \sqrt{2} $ **(e)** $\sqrt{2} - \sqrt{5}$ **(f)** $-\sqrt{5} + 2\sqrt{2}$

You can see for the (d) option, it still outputs as $3\sqrt{3} + \sqrt{2} $ but I expected it to be $3\sqrt{3} + \sqrt{2}$.

What is going on and why isn't it replacing it?

Here is a codepen example: https://codepen.io/jae_kingsley/pen/MWyWZbN

averageUsername123
  • 725
  • 2
  • 10
  • 22

2 Answers2

2

From W3Schools

If you are replacing a value (and not a regular expression), only the first instance of the value will be replaced

So you should probably use regular expressions for all replaces, not just the first one. Don't forget you'll have to escape the $:

.replace(/\s\$/g, '$')
Ry-
  • 218,210
  • 55
  • 464
  • 476
Danny Buonocore
  • 3,731
  • 3
  • 24
  • 46
1

Changing you code to following will work as it accounts for any $ with space before or after or none. So it will match $, $ , $, $ etc.

var changeString = function(markdownStr) {
  return markdownStr.replace(/`/g, "").replace(/\s*\$\s*/g, '$');
};
Dharman
  • 30,962
  • 25
  • 85
  • 135
dina
  • 937
  • 1
  • 12
  • 29