-2

I have a tinyMDE textarea that allows users to input text in Markdown. I also have an input that allows users to type a word, and when they click the "Submit" button, it'll run a boldWord() function that replaces all instances of that word with **word** (e.g. bolding the word in Markdown) in the original textarea. The issue is that .replace only bolds the first instance of input.value, but I want it to bold all instances. Here's my code:

function boldWord() {
            var input = document.getElementById("wordToBold"); // The input where users type a word
            var boldedText = document.getElementById("inputtext").value.replace(input.value, `**${input.value}**`); // inputtext is the ID of the Markdown textarea, input.value is the word the user wants bolded in that Markdown textarea
            tinyMDE.setContent(boldedText); // tinyMDE is a package that allows me to turn a textarea into Markdown
        }

For the replace line, I've tried this:

var boldedText = document.getElementById("inputtext").value.replace(/input.value/g, `**${input.value}**`);

...but it seems to interpret "input.value" as the string, "input.value", and not the variable it is referring to.

Rohan
  • 132
  • 4
  • 21
  • 2
    Have you considered [`.replaceAll()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll)? – ouroboring Feb 01 '21 at 19:57
  • @ouroboring thanks! that worked – Rohan Feb 01 '21 at 19:58
  • Does this answer your question? [JavaScript .replace only replaces first Match](https://stackoverflow.com/questions/3214886/javascript-replace-only-replaces-first-match) – Heretic Monkey Feb 01 '21 at 20:00

1 Answers1

1

Got it to work by using .replaceAll() (as suggested by @ouroboring)

Rohan
  • 132
  • 4
  • 21