简体   繁体   中英

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?

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/

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

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM