Reputation: 131
Having an issue where str.replace only works in the last element of my array here is the array:
["omao","carlton","judging"]
and here is my javascript function
function emoji(data){
//console.log(data);
$(".message-content").each(function(){
var elem = $(this);
var str = elem.html();
//var res = str.replace(":hey", '<img draggable="false" class="emoji jumboable" alt="emoji" src="https://discordchat.com/api/omao.png">');
for(var i = 0;i < data.length; i++){
var res = str.replace(":"+data[i], '<img draggable="false" title="Added using the WLA Poor Mans Nitro" class="emoji jumboable" alt="emoji" src="https://discordchat.com/api/'+data[i]+'.png" />');
elem.html(res);
}
});
}
When you run it, only :judging
gets replaced by the image, :omao
and :carlton
is ignored. Ive tried every "solution" I could find but all with the same issue.
Upvotes: 0
Views: 81
Reputation: 10617
Change
elem.html(res);
to
elem.append(res);
If running this multiple times (like .click()) you will want to put elem.empty()
right before your .each()
.
Upvotes: 0
Reputation: 12806
The problem you have is that you are repeating the replace on the original string, and not on the already changed string, which is why only the last iteration is the one that gets set
You can change it like so
var str = elem.html();
for(var i = 0;i < data.length; i++){
str = str.replace(":"+data[i], '<img draggable="false" title="Added using the WLA Poor Mans Nitro" class="emoji jumboable" alt="emoji" src="https://discordchat.com/api/'+data[i]+'.png" />');
}
// and set it only once
elem.html(res);
Upvotes: 3