Wednesday, June 13, 2012

Replace smiley code with images in a chat application in JavaScript

Many application supports adding smiley. In the text area, used for typing, we enter some text code like :) and on enter we can we can see in the history of chat this gets converted to smiley image. We can implement this by-
<script type="text/javascript">
    var replacement = { ":)": "<img src='smiley1.png' />", ":(": "<img src='smiley2.png' />", ":-)": "<img src='smiley3.png' />" };
    var string = ":) is a smily where :( another. :-) is one more";
    string = escape(string);
    for (var val in replacement)
        string = string.replace(new RegExp(escape(val), "g"), replacement[val]);
    string = unescape(string);
</script>
Special characters are not properly recognized in this case. That why escape and unescape is used.

No comments:

Post a Comment