在某些浏览器中,emoji表情不能正常显示,只能显示原始状态如下
为使表情正常显示,这里利用转码方法将emoji符号用图片替换1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61//对数据$scope.data.remark做表情替换处理,$scope.data.remark是包含emoji符号的字符串
var str=$scope.data.remark;
str=str.replace(rep,function(code) { //code即匹配到的emoji符号,对该符号通过_escapeToUtf32(code)转码,得到对应图片名,然后图片替换
return '<img class="emoji" style="vertical-align:middle" src="assets/img/emoji/'+_escapeToUtf32(code) + '.png">';
})
$scope.data.remark = str;
//用emoji符号的unicode码匹配emoji符号,例如270c匹配 victory hand符号
var rep =/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]|\u270c|\u261d/g;
//emoji 表情转码
function _escapeToUtf32(str) {
var escaped = [],
unicodeCodes = _convertStringToUnicodeCodePoints(str),
i = 0,
l = unicodeCodes.length,
hex;
for (; i < l; i++) {
hex = unicodeCodes[i].toString(16);
escaped.push('0000'.substr(hex.length) + hex);
}
return escaped.join('-');
}
function _convertStringToUnicodeCodePoints(str) {
var surrogate1st = 0,
unicodeCodes = [],
i = 0,
l = str.length;
for (; i < l; i++) {
var utf16Code = str.charCodeAt(i);
if (surrogate1st != 0) {
if (utf16Code >= 0xDC00 && utf16Code <= 0xDFFF) {
var surrogate2nd = utf16Code,
unicodeCode = (surrogate1st - 0xD800) * (1 << 10) + (1 << 16) + (surrogate2nd - 0xDC00);
unicodeCodes.push(unicodeCode);
}
surrogate1st = 0;
} else if (utf16Code >= 0xD800 && utf16Code <= 0xDBFF) {
surrogate1st = utf16Code;
} else {
unicodeCodes.push(utf16Code);
}
}
return unicodeCodes;
}
//Angularjs对字符串里面的html标签不会按照HTML去解析,会当做字符串显示,
//所以这里需要对字符串进行过滤,使字符串里面的标签能按照html解析
//新建过滤器trust2Html,这里使用$sce方法
app.filter('trust2Html', ['$sce',function($sce) {
return function(val) {
return $sce.trustAsHtml(val);
};
}])
//在页面里面显示经过图片替换的含emoji符号的字符串
<label ng-bind-html="data.remark|trust2Html"></label>
替换后结果
Emoji Unicode Tables