SimonDau
SimonDau

Reputation: 547

Javascript regex to match part of a string with item from a list

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?

Upvotes: 1

Views: 68

Answers (3)

Piyin
Piyin

Reputation: 1834

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/

Upvotes: 1

user4090029
user4090029

Reputation:

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>

Upvotes: 0

Linus Oleander
Linus Oleander

Reputation: 18157

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

Upvotes: 0

Related Questions