Answer the question
In order to leave comments, you need to log in
How to autocorrect text emoticons?
Hello.
I decided to add text emoticons to my chat that are rendered on the client. Two problems arose.
1. How to make a normal (including in terms of performance) replacement of the text representation ":-)" with <img src='id.gif' title=':-)' />
?
So far it works like this:
for (var i = 1; i < messages.smiliesList.length; i++){
for (var j = 0; j < messages.smiliesList[i].length; j++){
if (message.indexOf(messages.smiliesList[i][j],k)>-1){
message = message.split(messages.smiliesList[i][j]).join('<img src="img/smilies/'+messages.leadingZero(i)+'.gif" title="'+messages.smiliesList[i][j]+'" alt="'+messages.smiliesList[i][j]+'" />');
}
}
}
<img src='01.gif' title='O<img src='02.gif' title=':-)' />' />
. Answer the question
In order to leave comments, you need to log in
function regexpify(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
function getIndex(smiles, name) {
for (var i = 0, length = smiles.length; i < length; i++) {
if (smiles[i].name === name) {
return i;
}
}
console.error('not found', name);
return -1;
}
function process(message) {
var smiles = messages.smiliesList,
names = smiles.sort(function(a, b) {
// сортируем имена, так что бы более специфичные были вначале
return a.name.length > b.name.length ? 1 : -1;
}).map(function(smile) {
return regexpify(smile.name);
}),
regexp = new RegExp(names.join('|'), 'g');
return message.replace(regexp, function(name) {
return "<img src='/smiles/" + getIndex(smiles, name) + ".gif' alt='" + name + "'/>";
})
}
function replaceImages(message) {
return $('<div>').html(message).find('img').each(function(index, img) {
$(img).replaceWith($(img).attr('alt'));
}).end().html();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question