Hello I currently have this input box that takes the user's message and then appends it to a chat box like so:
$('#messageBox').on('keydown', function (evt) {
if( evt.keyCode == 13 ) {
$("#chatBox").append(`<div class="UserMessage"><span class="Author" style="color: #fffff;"><span id="ID"></span>User : </span><span class="message">${$( this ).val()}</span></div>`)
}
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="messageBox" type="text" placeholder="Your message here:">
<div id="chatBox" style="height: 350px; bottom: 50px;">
I would like to add a feature where it replaces any occurrences of a specific word with an image.
Please note that: The only option I have is to do the replacement after the message has been sent out to the chatBox, since this is just some client-side code, so I won't be able to do the replacement before the message is sent out to the chatBox.
For example, I want to replace any occurrences of :smileyface:
with an image link, while also keeping the text. For example; if the user enters Hello:smileyface:
it would turn into Hello(the image)
, if the user enters Hello :smileyface:
it would turn into Hello (the image)
and if the user enters just :smileyface:
it would turn into (the image)
.
So I tried something like this:
$("body").on('DOMSubtreeModified', "#chatBox", function() { // detects when a message it appended to the chatBox
$(".message").html(function (_, html) {
return html.replace(/:smileyface:/g,"<img src='https://i.stack.imgur.com/QrKSV.png' width ='35px'/>");
});
});
However when trying this I got a never-ending error in console, which froze the window:
Uncaught RangeError: Maximum call stack size exceeded.
How can I go about fixing this?