title: Insert HTML into user string and render it in React (and avoid XSS threat)
body: <p>User is supplying a string to our React app, and it's being displayed to other users. I want to search for some characters, and replace them with some HTML, like if I were to search for the word "special," I would turn it into:</p>
  
  <p><code>My &lt;span class="special-formatting"&gt;special&lt;/span&gt; word in a user string</code></p>
  
  <p>Previously I was performing this replacement and then inserting the result into the DOM with dangerouslySetInnerHTML. This of course is now giving me the issue of users being able to type and enter whatever HTML/Javascript they please right into the app and render it for everyone to see.</p>
  
  <p>I tried escaping the HTML characters to their entities, but dangerouslySetInnerHTML appears to render the HTML entities proper and not as an actual string. (EDIT: see below, this was the actual solution)</p>
  
  <p>Is there any way to convert their message to a pure string, still preserving the display of those special characters, but also insert my own HTML into the string? Trying to avoid running a script after each string is inserted to the DOM.</p>
  
  <hr>
  
  <p>Here's some more info regarding the current flow. All examples are pretty optimized to only show the relevant code.</p>
  
  <p>The user text is submitted to the database with this function:</p>
  
  <pre class="lang-js prettyprint-override"><code>handleSubmit(event) {
          event.preventDefault();
  
          var messageText = this.state.messageValue;
  
          //bold font is missing some common characters, fake way of making the normal font look bold
          if (this.state.bold == true) {
              messageText = messageText.replace(/\'/g, "&lt;span class='bold-apostrophe'&gt;'&lt;/span&gt;");
              messageText = messageText.replace(/\"/g, "&lt;span class='bold-quote'&gt;&amp;quot;&lt;/span&gt;");
              messageText = messageText.replace(/\?/g, "&lt;span class='bold-question'&gt;?&lt;/span&gt;");
              messageText = messageText.replace(/\*/g, "&lt;span class='bold-asterisk'&gt;*&lt;/span&gt;");
              messageText = messageText.replace(/\+/g, "&lt;span class='bold-plus'&gt;+&lt;/span&gt;");
              messageText = messageText.replace(/\./g, "&lt;span class='bold-period'&gt;.&lt;/span&gt;");
              messageText = messageText.replace(/\,/g, "&lt;span class='bold-comma'&gt;,&lt;/span&gt;");
          }
  
          Messages.insert({
              text: messageText,
              createdAt: new Date(),
              userId: user._id,
              bold: this.state.bold,
          });
  
      }
  </code></pre>
  
  <p>So, I did my replacements without issue, however at this point, the messageText string could still contain undesired, user-input HTML code.</p>
  
  <p>Then, our main app with the message list tries to render all the user messages:</p>
  
  <pre class="lang-js prettyprint-override"><code>render() {
      return (
          &lt;div ref="messagesList"&gt;
              {this.renderMessages()}
          &lt;/div&gt;
      );
  }
  </code></pre>
  
  <pre class="lang-js prettyprint-override"><code>renderMessages() {
      return [].concat(this.props.messages).reverse().map((message) =&gt; {
          return &lt;Message
              key={message._id}
              message={message} /&gt;;
          }
      });
  }
  </code></pre>
  
  <p>In Message.jsx is where I'm doing the final touches to the message string (certain changes I don't want saved into the database of messages) and inserting it into an element to return:</p>
  
  <pre class="lang-js prettyprint-override"><code>export default class Message extends React.Component {
      render() {
  
          var processedMessageText = this.props.message.text;
  
          //another find and replace to insert images for :image_name: strings, similar to how Discord inputs its emoji
          processedMessageText = processedMessageText.replace(/:([\w]+):/g, function (text) {
              text = text.replace(/:/g, "");
              if (text.indexOf("_s") !== -1) {
                  text = text.replace(/_s/g, "");
                  text = "&lt;img class='small-smiley' src='/smileys/small/" + text + ".png'&gt;";
                  return text;
              }
              else {
                  text = "&lt;img class='smiley' src='/smileys/" + text + ".png'&gt;";
                  return text;
              }
          });
  
          return (
              &lt;div&gt;
                  &lt;div className='username'&gt;{this.props.message.username}: &lt;/div&gt;
                  &lt;div className='text' dangerouslySetInnerHTML={{ __html: processedMessageText }}&gt;&lt;/div&gt;
              &lt;/div&gt;
          );
      }
  }
  </code></pre>
  
  <p>So again, if the user includes malicious HTML in their input string, it will travel through all of this and get output to the message list, which is real bad. I'm hoping there's some way I can perform these desired HTML insertions to their string, while also not rendering the HTML that they potentially input as actual HTML. I would also still like to show characters commonly used in HTML, like angle brackets (&lt;>), so I want to avoid outright stripping their input string of common HTML characters.</p>
  
  <hr>
  
  <p>Since the accepted answer doesn't have much detail, I'll post what I ended up doing here. I HTML encoded the characters suggested by <a href="https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html" rel="nofollow noreferrer">OWASP</a> before adding my own HTML and rendering it into an HTML element's content. I wanted to avoid using another library, so I just did this:</p>
  
  <pre><code>messageText = messageText.replace(/\&amp;/g, "&amp;amp;");
  messageText = messageText.replace(/&lt;/g, "&amp;lt;");
  messageText = messageText.replace(/&gt;/g, "&amp;gt;");
  messageText = messageText.replace(/\//g, "&amp;#x2F;");
  messageText = messageText.replace(/\'/g, "&amp;#x27;");
  messageText = messageText.replace(/\"/g, "&amp;quot;");
  </code></pre>
  
  <p>After doing so I was no longer able to insert anything malicious, and tested using various test strings from OWASP without issue.</p>