0

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.

2
  • Updated the snippet, there was a bug in pasting. Commented Oct 12, 2017 at 21:05
  • Don't forget to accept answers, seeing you have a zero acceptance rate, though you already asked more than 15+ answers Commented Oct 12, 2017 at 22:37

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Wowo this was humiliating. Thanks so much, problem solved
0

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().

1 Comment

from what I see, he problably has a html like :amao :carlton :judging (seeing he preloads the elements html content) And just wants to replace does strings inside the single element

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.