0

I am trying to insert a generated html form. The stuff to be replaced in this case is every occurance of COMMENTID. For some reason, sometimes when "COMMENTID" is in quotes like that, it does not replace. Why??? How do I fix this?

const htmlstr = `
<form method="post" id="subCommentFormCOMMENTID">
The id of this form is "COMMENTID"
</form>`;
  
  console.log(htmlstr.replace("COMMENTID",4));
  

This should yield the following:

<form method="post" id="subCommentForm4">
The id of this form is "4"
</form>

But instead it does this:

<form method="post" id="subCommentForm4">
The id of this form is "COMMENTID"
</form>
4
  • 2
    Because you're not asking for it to replace all instances. That's what the regular expression g flag is for: htmlstr.replace(/COMMENTID/g, "4") Commented Jun 10, 2019 at 19:53
  • @Pointy that solved it, thanks. Commented Jun 10, 2019 at 19:54
  • 1
    Pointy's suggestion works for me jsfiddle.net/j08691/582kuejx Commented Jun 10, 2019 at 19:56
  • yeah, I forgot to replace " with /, I was trying replace("/regex/g") Commented Jun 10, 2019 at 19:59

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.