Blogger Ever

Change words into icons or smiley using Javascript

Words into icons, well can be helpful for you to make comments or articles more colourful.

Writing a blog post with smiley, well not me or maybe you but there are people who like to put some spices to their blog posts. Often I use symbols like :P or :) which are quite known today because we all are online now. I am giving a glance on it and it all depends on you which words will change in what icon.

Well I am doing this one on keyup function however this works totally client side therefore CMS like Blogger and Tumblr can also take advantage of it. I created this input kind of stuff just to demonstrate the way it works. Here is the demo.
See the Pen Text or expressions to icons and smileys by Mohammad Hamza Dhamiya (@hamzadhamiya) on CodePen.

I am using Font Awesome which have a huge number of icons and can be easily used with specific codes, check this cheat sheet.

Lets create the word factory. All you need to do is to set the word and its icon specific code listed at cheat sheet of font awesome. If you got some HTML code or some text or specific code of any other icon font you can use it quite easily.

var emojiData = {
    'Plane': '',
    'smile': '',
    'email': ''
Above is the demo of the word factory. If "Plane" is in the content then it would be replaced with &#xf072 which is the code for font awesome plane icon. Same goes with others. This word factory let you set specific amount of words to be replaced, use as many as you want.

Next part is to get all these keys and their values to be replaced. loop iterates through each key and value.

function emojify(emoji, EmoInput) {
    var article = document.querySelector('.content');
    article.innerHTML = EmoInput.value;
    for (var emojiText in emoji) {
        var myExp = new RegExp(emojiText, 'i');
        var textMatch = article.innerText.replace(myExp, emoji[emojiText]);
        article.innerHTML = textMatch;

A regex object is created, then using replace function the regular expression filters the string that is the content and then whatever the key returns, its value is replaced.

You know the best part?

Perhaps, Font Awesome is not enough for all your needs, there are other fonts too. Use SVGs using link tag or even use images for that. You can use GIFs which maybe more funnier part of this stuff.

Wordpress is a quite right system that let you do anything with comment form. If your blog niche is web development then your comment system might have options to accept different tags like pre or code. This let user input the code in nice way. But I've seen certain blogs with emoji bar at top which let user add emoji to their comments. You can use this technique to make it work.

Got any better thoughts hit me in comment.

2013-2016 Copyright Blogger E\ver . Coded, managed and founded by Mohammad Hamza (@hamzadhamiya) . Hosted on Blogger and fonts used are Raleway and Open Sans.