I have a function that replaces text smilies etc. with image emoticons
How can I make this case-INsensitive? I have tried using "gi" and "ig" at the replacer, but it does'nt seem to make a difference
var emots = {
':)' : 'smile',
':-)' : 'smile',
';)' : 'wink',
';-)' : 'wink',
':(' : 'downer',
':-(' : 'downer',
':D' : 'happy',
':-D' : 'happy',
'(smoke)' : 'smoke',
'(y)' : 'thumbsup',
'(b)' : 'beer',
'(c)' : 'coffee',
'(cool)' : 'cool',
'(hehe)' : 'tooth',
'(haha)' : 'tooth',
'(lol)' : 'tooth',
'(pacman)' : 'pacman',
'(hmm)' : 'sarcastic',
'(woot)' : 'woot',
'(pirate)' : 'pirate',
'(wtf)' : 'wtf'
};
function smile(str){
var out = str;
for(k in emots){
out = out.replace(k,'<img src="/emoticons/'+emots[k]+'.gif" title="'+k+'" />','g');
}
return out;
};
Change:
out = out.replace(k,'<img src="/emoticons/'+emots[k]+'.gif" title="'+k+'" />','g');
To:
out = out.replace(new RegExp(k.replace(/[-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), 'ig'), '<img src="/emoticons/'+emots[k]+'.gif" title="'+k+'" />');
Regex escaping function taken from this answer Escape string for use in Javascript regex
This is a bit trickier than it appears on the surface. Following is a complete solution. It uses only one regex search on the target string, for simplicity and efficiency.
Note that, because it's case insensitive (eg, (hehe)
and (HeHe)
are treated the same), :-d
is also treated the same as :-D
.
var emots = {
':)' : 'smile',
':-)' : 'smile'
// Add the rest of your emoticons...
};
// Build the regex that will be used for searches
var emotSearch = [];
for (var p in emots) {
if (emots.hasOwnProperty(p)) {
emotSearch.push(p.replace(/[-[{()*+?.\\^$|]/g, '\\$&'));
if (p !== p.toLowerCase()) {
emots[p.toLowerCase()] = emots[p];
}
}
}
emotSearch = RegExp(emotSearch.join('|'), 'gi');
function smile(str) {
return str.replace(emotSearch, function ($0) {
var emot = $0.toLowerCase();
if (emot in emots) {
return '<img src="/emoticons/' + emots[emot] + '.gif" title="' + $0 + '" />';
}
return $0;
});
}
或者在运行检查之前在输入上使用.toLowerCase()?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.