Replace only part of text in jQuery function

134 Views Asked by At

I'm using this solution for replace a list of emojies:

(function($){
   var emojies = ["smile", "smiley", "grin", "joy"];
   var emojiRegex = new RegExp(":("+ emojies.join("|") +"):","g");
   $.fn.toEmoji = function(){
        return this.each(function() {
            this.innerHTML = this.innerText.replace(emojiRegex,function(fullmatch,match){
                return '<span class="emoji '+match.toLowerCase()+'"></span>';
            });                
        });
   };
})(jQuery);
//And use like
$(document).ready(function(){
    $(".content div").toEmoji();
});

But this replace all the content div (this.innerHTML...), however, there is no way I do it and just replace the :emoji: and not all the text?

Because, if the text has a break line, for ex:

Hi!

How are you?

Will replace for:

Hi! How are you?

In addition to other problems... So, how to do?

1

There are 1 best solutions below

0
On BEST ANSWER

The problem is you are reading from the DIV as innerText which will not include the HTML tags like <br/>. Instead, you can read from the DIV with innerHTML like so:

   $.fn.toEmoji = function(){
        return this.each(function() {
            this.innerHTML = this.innerHTML.replace(emojiRegex,function(fullmatch,match){
                return '<span class="emoji '+match.toLowerCase()+'"></span>';
            });                
        });
   };

Note this.innerHTML.replace instead of this.innerText.replace!

JSFiddle: http://jsfiddle.net/ybj7gpn6/ (inspect HTML after clicking button to see spans are present -- looks like blank space)