Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
string-kit
Advanced tools
A string manipulation toolbox, featuring a string formatter (inspired by sprintf), a variable inspector (output featuring ANSI colors and HTML) and various escape functions (shell argument, regexp, html, etc).
string-kit is a versatile JavaScript library for string manipulation. It provides a wide range of utilities for working with strings, including formatting, padding, alignment, and more.
String Formatting
The `format` function allows you to format strings using placeholders, similar to printf in C. This is useful for creating dynamic strings based on variable values.
const string = require('string-kit');
console.log(string.format('%s is %d years old.', 'Alice', 30));
String Padding
The `pad` function pads a string to a specified length with a given character. This is useful for aligning text in console output or creating fixed-width string representations.
const string = require('string-kit');
console.log(string.pad('Hello', 10, ' '));
String Alignment
The `align` function aligns a string within a specified width, either left, right, or center. This is useful for formatting text in tables or other structured formats.
const string = require('string-kit');
console.log(string.align('Hello', 10, 'center', ' '));
String Truncation
The `truncate` function shortens a string to a specified length, optionally adding an ellipsis or other suffix. This is useful for displaying previews or summaries of longer text.
const string = require('string-kit');
console.log(string.truncate('This is a long string', 10));
The `string` package provides a wide range of string manipulation utilities, including trimming, padding, and formatting. It is similar to string-kit but offers a different API and some additional features.
Lodash is a utility library that provides a wide range of functions for working with arrays, objects, and strings. It includes string manipulation functions like padding, truncation, and case conversion. While it is more general-purpose than string-kit, it offers similar string manipulation capabilities.
underscore.string is a string manipulation library that extends Underscore.js with additional string functions. It provides utilities for trimming, padding, formatting, and more. It is similar to string-kit but designed to work seamlessly with Underscore.js.
A string manipulation toolbox, featuring a string formatter (inspired by sprintf), a variable inspector (output featuring ANSI colors and HTML) and various escape functions (shell argument, regexp, html, etc).
Use Node Package Manager:
npm install string-kit
String
a string containing some sprintf()
-like formatingmixed
a variable list of arguments to insert into the formatStringThis function is inspired by the C
's sprintf()
function.
Basicly, if formatString
includes format specifiers (subsequences beginning with %), the additional arguments
following formatString
are formatted and inserted in the resulting string replacing their respective specifiers.
Also it diverges from C
in quite a few places.
New: Since v0.3.x we can add styles markup (color, bold, italic, and so on...) using the ^
caret.
See the format markup documentation.
Basic usage:
var format = require( 'string-kit' ).format ;
console.log( format( 'Hello %s %s, how are you?' , 'Joe' , 'Doe' ) ) ;
// Output: 'Hello Joe Doe, how are you?'
Specifiers:
%%
write a single %%s
to string, with sanitizer%S
to string, with ^
interpretation%r
to raw string, without any sanitizer%n
to natural: output the most natural representation for this type%N
to even more natural: avoid type hinting marks like bracket for array%f
to (float) number%k
to number with metric system prefixes (like k, M, G, and so on...)%e
to exponential “E notation” (e.g. 13 -> 1.23e+2)%K
to scientific notation (e.g. 123 -> 1.23 × 10²)%i
to integer%d
alias of %i
(C's printf()
compatibility)%u
to unsigned integer%U
to unsigned positive integer (>0)%P
to (absolute) percent (e.g.: 1.25 -> 125% ; 0.75 -> 75%)%p
to relative percent (e.g.: 1.25 -> +25% ; 0.75 -> -25%)%t
to time duration, convert ms into H:min:s%m
to degrees/minutes/seconds notation%h
to unsigned hexadecimal%x
to unsigned hexadecimal, force pairs of symbols (e.g. 'f' -> '0f')%o
to unsigned octal%b
to unsigned binary%X
string/binary/buffer to hexadecimal: convert a string into hex charcodes, force pair of symbols (e.g. 'f' -> '0f' ; 'hello' -> '68656c6c6f')%z
string/binary/buffer to base64%Z
string/binary/buffer to base64url%O
for objects (call string-kit's inspect() with ultra-minimal options)%I
call string-kit's inspect()%Y
call string-kit's inspect(), but do not inspect non-enumerable%E
call string-kit's inspectError()%J
to JSON (call JSON.stringify()%D
drop, the argument does not produce anything but is eaten anyway%F
filter function existing in the this context, e.g. %[filter:%a%a]F%a
argument for a filter functionFew examples:
var format = require( 'string-kit' ).format ;
console.log( format( 'This company regains %d%% of market share.' , 36 ) ) ;
// Output: 'This company regains 36% of market share.'
console.log( format( '11/8=%f' , 11/8 ) ) ;
// Output: '11/8=1.375'
console.log( format( 'Hexa %h %x' , 11 , 11 ) ) ;
// Output: 'Hexa b 0b'
We can insert a number between the % sign and the letter of the specifier, this way, rather than using the next argument, it uses the Nth argument, this is the absolute position:
console.log( format( '%2s%1s%3s' , 'A' , 'B' , 'C' ) ) ; // 'BAC'
Also, the internal pointer is moved anyway, so the Nth format specifier still use the Nth argument if it doesn't specify any position:
console.log( format( '%2s%s%s' , 'A' , 'B' , 'C' ) ) ; // 'BBC'
If the number is preceded by a plus or a minus sign, the relative position is used rather than the absolute position.
console.log( format( '%+1s%-1s%s' , 'A' , 'B' , 'C' ) ) ; // 'BAC'
Use case: language.
var hello = {
en: 'Hello %s %s!' ,
jp: 'Konnichiwa %2s %1s!'
} ;
console.log( format( hello[ lang ] , firstName , lastName ) ) ;
// Output the appropriate greeting in a language.
// In japanese the last name will come before the first name,
// but the argument list doesn't need to be changed.
Some specifiers accept parameters: there are between bracket, inserted before the letter, e.g.: %[L5]s
.
See the specifier parameters section.
The mysterious %[]F
format specifier is used when we want custom formatter.
Firstly we need to build an object containing one or many functions.
Then, format()
should be used with call()
, to pass the functions collection as the this context.
The %[
is followed by the function's name, followed by a :
, followed by a variable list of arguments using %a
.
It is still possible to use relative and absolute positionning.
The whole format specifier is finished when a ]F
is encountered.
Example:
var filters = {
fxy: function( a , b ) { return '' + ( a * a + b ) ; }
} ;
console.log( format.call( filters , '%s%[fxy:%a%a]F' , 'f(x,y)=' , 5 , 3 ) ) ;
// Output: 'f(x,y)=28'
console.log( format.call( filters , '%s%[fxy:%+1a%-1a]F' , 'f(x,y)=' , 5 , 3 ) ) ;
// Output: 'f(x,y)=14'
A parameter consists in a letter, then one character (letter or not letter), that could be followed by any number of non-letter characters.
E.g. %[L5]s
, the L parameter that produce left-padding to force a 5 characters-length.
A special parameter (specific for that specifier) consists in any number of non-letter characters and must be the first parameter. E.g.:
%[.2]f
, the special parameter for the f specifier (float), it rounds the number to the second decimal place.%[.2L5]f
, mixing both the special and normal parameters, the special parameter comes first (round the the second decimal place),
then comes the generic and normal parameter L (left-padding)When a parameter needs a boolean, +
denotes true, while -
denotes false.
Generic parameters -- they almost always exists for any specifier and use an upper-case parameter letter:
Specifier's specific parameters :
%[3]f
(12.345 -> 12.3)%[3.]f
(12345 -> 12000)%[.2]f
(1.2345 -> 1.23)%[.2!]f
(12.9 -> 12.90 ; 12 -> 12.00) (useful for prices)%[.2?]f
(12.9 -> 12.90 ; 12 -> 12)%[z5]f
(12 -> 00012)%[g,]f
(123456 -> 12,345)%[g]f
(123456 -> 12 345)%[c+]I
.Since v0.3.x we can add styles (color, bold, italic, and so on...) using the ^
caret:
var format = require( 'string-kit' ).format ;
console.log( format( 'This is ^rred^ and ^bblue^:!' , 'Joe' , 'Doe' ) ) ;
// Output: 'This is red and blue!' with 'red' written in red and 'blue' written in blue.
Style markup:
^^
write a single caret ^
^b
switch to blue^B
switch to bright blue^c
switch to cyan^C
switch to bright cyan^g
switch to green^G
switch to bright green^k
switch to black^K
switch to bright black^m
switch to magenta^M
switch to bright magenta^r
switch to red^R
switch to bright red^w
switch to white^W
switch to bright white^y
switch to yellow (i.e. brown or orange)^Y
switch to bright yellow (i.e. yellow)^_
switch to underline^/
switch to italic^!
switch to inverse (inverse background and foreground color)^+
switch to bold^-
switch to dim^:
reset the style^
(caret followed by a space) reset the style and write a single space^#
background modifier: next color will be a background color instead of a foreground color,
e.g.: 'Some ^#^r^bred background
text' will write red background in blue over red.Note: as soon as the format string has one style markup, a style reset will be added at the end of the string.
String
a string containing some sprintf()
-like formatingIt just counts the number of format specifier in the formatString
.
Object
display options, the following key are possible:
String
this is the style to use, the value can be:
Set
of blacklisted object prototype (will not recurse inside it)Set
of blacklisted property names (will not even display it)mixed
anything we want to inspect/debugIt inspect a variable, and return a string ready to be displayed with console.log(), or even as HTML output.
It produces a slightly better output than node's util.inspect()
, with more options to control what should be displayed.
Since options
come first, it is possible to use bind()
to create some custom variable inspector.
For example:
var colorInspect = require( 'string-kit' ).inspect.bind( undefined , { style: 'color' } ) ;
String
the string to filterIt escapes the string so that it will be suitable as a shell command's argument.
String
the string to filterIt escapes the string so that it will be suitable to inject it in a regular expression's pattern as a literal string.
Example of a search and replace from a user's input:
var result = data.replace(
new RegExp( stringKit.escape.regExp( userInputSearch ) , 'g' ) ,
stringKit.escape.regExpReplacement( userInputReplace )
) ;
String
the string to filterIt escapes the string so that it will be suitable as a literal string for a regular expression's replacement.
String
the string to filterIt escapes the string so that it will be suitable as HTML content.
Only < > &
are replaced by HTML entities.
String
the string to filterIt escapes the string so that it will be suitable as an HTML tag attribute's value.
Only < > & "
are replaced by HTML entities.
It assumes valid HTML: the attribute's value should be into double quote, not in single quote.
String
the string to filterIt escapes all HTML special characters, < > & " '
are replaced by HTML entities.
String
the string to filterIt escapes all ASCII control characters (code lesser than or equals to 0x1F, or backspace).
Carriage return, newline and tabulation are respectively replaced by \r
, \n
and \t
.
Other characters are replaced by the unicode notation, e.g. NUL
is replaced by \x00
.
Full BDD spec generated by Mocha:
FAQs
A string manipulation toolbox, featuring a string formatter (inspired by sprintf), a variable inspector (output featuring ANSI colors and HTML) and various escape functions (shell argument, regexp, html, etc).
We found that string-kit demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.