This small library limits a string to a specified width:
- Truncates the string if the length is more than the limit
- Pads the string using custom characters if the length is less than the limit, on the right or left
- Works with unicode characters (Emojis, etc)
🔥 Please note that this library is built for accuracy, not performance. It uses complex regular expressions to
calculate the string length and perform other operations which are not particularly super-jawdropping-fast like
the native String.prototype.length
.
Install
$ npm install limit-string-length --save
And import it in your awesome node app:
// ES2015+; // CommonJSvar limit = ;
Usage
// Truncate:; // "Life's like a box of" // Pad:; // "Make emojis great again💩💩💩" // Pad Left:; // "++++++What are you looking at?" // Unicode Aware:; // "🤔🤔"
Parameters
function limit(str[, limit[, padStr[, padPosition]]])
Param | Type | Default | Description |
---|---|---|---|
str | String |
none | The string to be limited |
limit | Number |
16 |
Desired string length |
padStr | String |
"#" |
Character to pad the output with |
padPosition | String |
"right" |
Pad position: "right" or "left" |
Test
$ npm run test
Changelog
Version | Date | Notes |
---|---|---|
0.0.9 | 2016-07-28 | Fixed unicode string length issue |
0.0.8 | 2016-07-26 | First usable release |
License
This software is released under the MIT License.
Copyright © 2016 Sallar Kaboli <sallar.kaboli@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.