Replace only part of text in jQuery function

I am using this solution to replace the emojies list:

(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 will replace all the content of the div ( this.innerHTML...

), however I cannot do that and just replace: emoji: and not all the text?

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

Hello!

How are you?

Will be replaced by:

Hello! How are you?

In addition to other problems ... So how do you do this?

+3


source to share


1 answer


The problem is that you are reading from a DIV as innerText

that will not include HTML tags like <br/>

. Instead, you can read from the DIV with the innerHTML

following:

   $.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/ (check the HTML after clicking the button to see if spaces are present - looks like empty space)

+4


source







All Articles