GithubHelp home page GithubHelp logo

unicode-byte-truncate's Introduction

unicode-byte-truncate

Truncate a string to a given byte size by removing bytes from the right while making sure not to slice in the middle of a multi-byte unicode character.

Build status js-standard-style

Installation

npm install unicode-byte-truncate --save

Usage

var trunc = require('unicode-byte-truncate')

var str = 'foo🎉bar' // 10 byte string - byte 4 to 7 is a single character

console.log(trunc(str, 4)) // `foo` == 0x666F6F (3 bytes)
console.log(trunc(str, 5)) // `foo` == 0x666F6F (3 bytes)
console.log(trunc(str, 6)) // `foo` == 0x666F6F (3 bytes)
console.log(trunc(str, 7)) // `foo🎉` == 0x666F6FF09F8E89 (7 bytes)

API

The unicode-byte-truncate module exposes a single trunc function.

result = trunc(string, maxBytes)

Given a string and a maxBytes integer greater than or equal to zero, the trunc function will slice characters off the end of the string to ensure that it doesn't contain more bytes than specified by the maxBytes argument.

The truncated string will be returned as the result.

The trunc function is multi-byte unicode aware and will never cut up surrogate pairs. This means that the result may contain fewer bytes than specified by the maxBytes argument.

License

MIT

unicode-byte-truncate's People

Contributors

watson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

astorm

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.