読者です 読者をやめる 読者になる 読者になる

javascript truncate multibyte

export function isSurrogatePear( upper, lower ) {
return 0xD800 <= upper && upper <= 0xDBFF && 0xDC00 <= lower && lower <= 0xDFFF
}
export function mbStrlen( str ) {
var ret = 0
for (var i = 0; i < str.length; i++,ret++) {
var upper = str.charCodeAt(i)
var lower = str.length > (i + 1) ? str.charCodeAt(i + 1) : 0
if ( isSurrogatePear( upper, lower ) ) { i++; }
}
return ret;
}
export function mbSubstr( str, begin, end ) {
var ret = ''
for (var i = 0, len = 0; i < str.length; i++, len++) {
var upper = str.charCodeAt(i)
var lower = str.length > (i + 1) ? str.charCodeAt(i + 1) : 0
var s = ''
if( isSurrogatePear( upper, lower ) ) {
i++;
s = String.fromCharCode( upper, lower )
} else {
s = String.fromCharCode( upper )
}
if ( begin <= len && len < end ) { ret += s; }
}
return ret
}

export function truncate(str, end, trancation = '...') {
if (mbStrlen(str) <= end) {
return str
}
return mbSubstr(str, 0, end) + '...'
}

 

qiita.com