/**
* 한글자 당 byte 구하기
* @param {string} charValue 문자열
* @returns {number} 바이트
*/
export const charByteSize = (charValue) => {
if (charValue == null || charValue.length == 0) {
return 0
}
let charCode = charValue.charCodeAt(0)
if (charCode <= 0x00007f) {
return 1
} else if (charCode <= 0x0007ff) {
return 2
} else if (charCode <= 0x00ffff) {
return 3
} else {
return 4
}
}
/**
* 한글자 당 byte 구하기
* @param {string} charValue 문자열
* @returns {number} 바이트
*/
export const charByteSize = (charValue) => {
if (charValue == null || charValue.length == 0) {
return 0
}
let charCode = charValue.charCodeAt(0)
if (charCode <= 0x00007f) {
return 1
} else if (charCode <= 0x0007ff) {
return 2
} else if (charCode <= 0x00ffff) {
return 3
} else {
return 4
}
}
/**
* 지정된 byte만큼 문자열 자르기
* @param {string} str 문자열
* @param {number} len 자를 byte 개수
* @returns {string} 잘린 문자열
*/
export const cutByteLength = (str, len) => {
if (str == null || str.length == 0) {
return ''
}
let size = 0
let rIndex = str.length
for (let i = 0; i < str.length; i++) {
size += charByteSize(str.charAt(i))
if (size == len) {
rIndex = i + 1
break
} else if (size > len) {
rIndex = i
break
}
}
return str.substring(0, rIndex)
}
개인 공부를 정리하는 블로그입니다.
잘못된 개념을 게시하지 않도록 주의하지만 오류가 있을 수 있습니다.