'How should I insert specific characters to prevent discord formatting?

I am working on a small webpage that formats the text you input, for a Minecraft server I am involved in. The text is then meant to be copied to a discord channel. The problem is Discord's formatting which allows some characters can make the text underlined or bold. Some Minecraft usernames have underscored, and I wanted to make a loop that adds "" in front of any underscores so discord ignores them. This is what I came up with:

// example for result
var result = "__MinecraftUsername__";

// the loop
while (result.includes("_") == true) {
  result = i(result, result.indexOf("_"), "\");
}

// in the actual code this is put into the html
alert(result);

// function to add characters at a specific index
function i(str, index, value) {
    return str.substr(0, index) + value + str.substr(index);
}
When I run this code the webpage becomes unresponsive. I am very new to JavaScript and I am sorry if this is a really silly mistake.


Solution 1:[1]

Try using a javascript function like the one in this example... that will eliminate the while loop.

But as a suggestion, why not wrap the minecraft names with back-quotes? That may preserve the name's characters, without trying to treat them as markdown codes. As an example of wrapping with back-quotes preserves the characters that would normally be treated as markdown: __some_*minecraft*_name__.

I'm using jQuery just to display the results, so you can ignore the jQuery.

var mcName = "_some_minecraft_name_";
$(".original").text(mcName);

var results = mcName.replaceAll("_", "\");
$(".sample").text(results);


/**
 * This change to the javascript String prototype adds a replaceAll
 * function to the String.  This prevents the need to do a
 * split().join() explicitly.
 *
 * @param search
 * @param replace
 * @returns
 */
String.prototype.replaceAll = function( search, replace ) {
    var results = this.split(search).join(replace);

    return results;
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="original"></p>
<p class="sample"></p>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1