1

I've got stuck with this one. Got a string, just as this one:

<div id="result">Hello there Paul :) How are you</div>

Now I'd like to replace the smiley face with an image. If that was a single instance it wouldn't give me any headache. This is what I've got:

$.fn.emoji = function(){
    var keys = ':-D|:D|:-)|:)|;-)|;)|:-O|:o|:-P|:p|:-(|:(|:-S|:s|:-l|:l|B-)|B)|*-)|*)|8ol|8l';

    return this.each(function(){
       var regex = new RegExp('(' + keys + ')', 'g');
       $(this).html($(this).html().replace(regex, <img />));
    });
};

What I'm trying to do is find if any of the keys are within the string and then replace it with an image. But my RegExp object is completely wrong. Anyone's able to fix it?

SimonDau
  • 337
  • 3
  • 7
  • Even if you get this working, wouldn't it replace all smileys with the same image? Is this behavior really what you want? – Arg0n Nov 20 '15 at 20:09

3 Answers3

1

You have to escape the special characters on your RegExp. Here you have your modified code so you don't have to bother with all that escaping:

$.fn.emoji = function(){
    var keys = [':-D',':D',':-)',':)',';-)',';)',':-O',':o',':-P',':p',':-(',':(',':-S',':s',':-l',':l','B-)','B)','*-)','*)','8ol','8l'];
    for(var key in keys){
        //Taken from http://stackoverflow.com/a/6969486/5503625
        keys[key] = keys[key].replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
    }
    keys = '('+keys.join(')|(')+')';

    return this.each(function(){
       var regex = new RegExp('(' + keys + ')', 'g');
       $(this).html($(this).html().replace(regex, '<img />'));
    });
};

https://jsfiddle.net/6s3h1j3j/

Piyin
  • 1,765
  • 1
  • 14
  • 23
0

You need to group you emojs like /(:D)|(:-D)/. ) also needs to be escaped, like /\)/.

Linus Oleander
  • 16,922
  • 13
  • 62
  • 97
0

It didn't work cause of containing some special characters: (, ), *.

So, you need to add \ before that characters.

Example: Clicking on the <div>

$('div').click(function () {
  alert($(this).text().replace(/:\)|:-\)/g, '<img />'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Hello there Paul :) How are you :-) </div>