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?

1
  • Even if you get this working, wouldn't it replace all smileys with the same image? Is this behavior really what you want? Commented Nov 20, 2015 at 20:09

3 Answers 3

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/

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.