Introduction
Despite the fact that javascript is an excellent programming language, it sometimes suffers from a lack of functionalities. Unlike others programming language, it doesn’t have a native string replacer and that’s why I’ve written the @rimiti/stimmy (Github) package and this article.
Why @rimiti/stimmy?
Used in many production packages, it have been written to be safe and fully customizable.
Benefits:
- Very light (8kb)
- Can replace string variables from an object.
- Can replace string variables from an array.
- Pattern customizable.
- Doesn’t have dependencies.
- 100% of code coverage
- …
How to use it?
Stimmy is CommonJS and ES6 compliant, in this case you can import or require it without .default.
Like all NodeJS packages, you need to import it before using it.
1 2 3 4 5 |
// CommonJS const stimmy = require('@rimiti/stimmy'); // ES6 import stimmy from '@rimiti/stimmy'; |
After that, you just have to instantiate it:
1 2 |
// As default, it use the {myVariable} pattern const replacer = stimmy(); |
Stimmy provides two ways for replacing your variables.
From an array:
1 2 3 4 5 |
replacer('This {0} is {1}!', ['module', 'awesome']); // This module is awesome! replacer('{0}% of code coverage, it\'s {1}...', [100, 'so amazing']); // 100% of code coverage, it's so amazing... |
From object:
1 2 3 4 5 |
replacer('{timmy} My hobby is {hobby}...', {timmy: 'Timmmmmmmyy !!', hobby: 'running'}); // Timmmmmmmyy !! My hobby is running... replacer('My name is {name}, I\'m {age}.', {name: 'stimmy', age: 25}); // My name is stimmy, I'm 25. |
Ok, but how to customize the replacement pattern?
In case you want to change the default pattern, you just have to pass it as parameter when you assign the replacer, example:
1 2 |
// If you want to customized default pattern (ex: {{myVariable}} const replacer = stimmy('{{', '}}') |
From an array:
1 2 3 4 5 |
replacer('This {{0}} is {{1}}!', ['module', 'awesome']); // This module is awesome! replacer('{0}% of code coverage, it\'s {{1}}...', [100, 'so amazing']); // 100% of code coverage, it's so amazing... |
From object:
1 2 3 4 5 |
replacer('{{timmy}} My hobby is {{hobby}}...', {timmy: 'Timmmmmmmyy !!', hobby: 'running'}); // Timmmmmmmyy !! My hobby is running... replacer('My name is {{name}}, I\'m {{age}}.', {name: 'stimmy', age: 25}); // My name is stimmy, I'm 25. |
If you want more examples or snippets, you can check the official repository.
Leave a comment