250x250
Notice
Recent Posts
Recent Comments
- Today
- Total
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
Tags
- EC2
- JavaScript
- Express
- til
- Find
- mongodb
- jsonwebtoken
- https
- TailwindCSS
- findByIdAndDelete
- RDS
- double quote
- mongoose
- flutter
- nginx
- moment
- css
- TypeScript
- wil
- single quote
- Node.js
- atlas
- MYSQL
- sequelize
- async
- clipBehavior
- Nodejs
- certbot
- await
- AWS
Link
Archives
기억 휘발 방지소
[Node.js] String의 Bytes Length 구하기 본문
728x90
반응형
문자의 Bytes 길이를 쉽게 구하는 방법이 있습니다.
buffer.byteLength를 사용하면 됩니다.
const korBytesLength = Buffer.byteLength('안녕');
const engBytesLength = Buffer.byteLength('hello');
console.log(korBytesLength); // 6
console.log(engBytesLength); // 5
근데 영어는 글자당 1 bytes로 계산되는데 한글의 경우 글자당 3 bytes로 계산됩니다.
한글을 글자당 2 bytes로 계산하려면 다음과 같이 할 수 있습니다.
function getBytes(str) {
let character;
let charBytes = 0;
for (let i = 0; i < str.length; i += 1) {
character = str.charAt(i);
if (escape(character).length > 4) charBytes += 2;
else charBytes += 1;
}
return charBytes;
}
console.log(getBytes('안녕')); // 4
console.log(getBytes('hello')); // 5728x90
반응형
'Web > Node.js' 카테고리의 다른 글
| Jest를 이용하여 API 테스트코드 작성하기 (초간단) (0) | 2022.11.11 |
|---|---|
| Express + Nginx (with 윈도우) (0) | 2022.04.27 |
| 코드 포매터(Formatter)와 린터(Linter) (0) | 2022.03.14 |
| node-schedule을 사용한 작업 스케줄링 (0) | 2022.03.10 |
| Node.js와 AWS RDS 연동 with Express, Prisma (0) | 2022.02.09 |