string-byte-cutter
v1.0.1
Published
Safely truncate/substring strings by UTF-8 byte length without character corruption.
Maintainers
Readme
string-byte-cutter
Why use string-byte-cutter? Databases, network packets, and file systems often enforce byte limits (e.g., VARCHAR(255) bytes). Standard JS string slicing (
string.substring(0, 255)) measures character counts, not byte length. Truncating multibyte characters (like emojis 🚀 or non-Latin alphabets) arbitrarily can cut characters in half, producing corrupted unicode placeholders.
A safe string byte truncator that trims strings to a maximum byte capacity while ensuring slices are cut on valid UTF-8 character boundaries.
⚡ Features
- Accurate UTF-8 byte calculations
- Prevents half-cut corrupted characters or broken emojis
- Fast, zero-dependency string byte slice engine
📦 Installation
npm i string-byte-cutter🚀 Usage
import { cutByBytes, byteLength } from 'string-byte-cutter';
const longStr = 'Hello World 🚀🔥🌟'; // Emojis are 4-bytes each
console.log('Byte length:', byteLength(longStr));
const truncated = cutByBytes(longStr, 14); // Truncates safely on valid character boundary
console.log(truncated); // "Hello World " (Doesn't leave half-cut broken bytes)⚙️ API Reference
cutByBytes(str, maxBytes)
- Truncates
strto be at mostmaxBytesin UTF-8 byte length.
byteLength(str)
- Returns actual UTF-8 byte length of
str.
📺 Demonstration

📄 License
MIT License.
