前几天在做微信分享的时候,发现带有部分表情的内容,安卓端可以分享有乱码,但是在iOS端分享直接报错
String contained an illegal UTF-16 sequence
也就是字符串中包含非法的UTF-16字符。
解决方案如下:
const replacement = '\ufffd';
// https://gist.github.com/mathiasbynens/bbe7f870208abcfec860
const loneSurrogates = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|([^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/g;
// string sanitizes the given str by replacing invalid UTF-16 code unit
// sequences with the unicode replacement character. Returns a new string.
//用 \ufffd 取代无效的增补字节的,无效的高位或者低位
exports.string = function(str) {
return str.replace(loneSurrogates, '$1' + replacement);
}