For my recent project, I need a trick to split strings contain English words to separate words. My stack is Node.js and no packages have been developed for my need.
For example, I need this string "youneedtolearnfromyourmistakes" split to words "You Need To Learn From Your Mistakes".
For this reason, I began searching for the development of a package for my need. And finally, with some open source project, I develop a package for split strings to words. The package called "wordsninja" has been released.
https://github.com/parsakafi/wordsninja
https://npmjs.com/package/wordsninja
Install
npm install wordsninja --save
Load package
const WordsNinjaPack = require('wordsninja');
const WordsNinja = new WordsNinjaPack();
Load dictionary
await WordsNinja.loadDictionary(); // First load dictionary
Add word(s)
WordsNinja.addWords('new word');
Parameters
-
word
: The word(s) (string|array)
Split sentence
let words = WordsNinja.splitSentence(string, {camelCaseSplitter, capitalizeFirstLetter, joinWords});
Parameters
-
string
: The string for split -
options
-
camelCaseSplitter
: Split by Camel Case, Default isfalse
(optional) -
capitalizeFirstLetter
: Capitalize First Letter, Default isfalse
(optional) -
joinWords
: Return join words as sentence, Default isfalse
(optional)
-
Example
(async () => {
await WordsNinja.loadDictionary(); // First load dictionary
let string = 'youneedtolearnfromyourmistakes';
let words = WordsNinja.splitSentence(string);
console.log(words);
})();
Result
[ 'you', 'need', 'to', 'learn', 'from', 'your', 'mistakes' ]
More options
let string = 'youneedtolearnfromyourmistakes';
let words = WordsNinja.splitSentence(string,
{
camelCaseSplitter: true, // Frist camel case spliting
capitalizeFirstLetter: true, // Capitalize first letter of result
joinWords: true // Join words
}
);
console.log(words);
Result
You Need To Learn From Your Mistakes
Add Word(s)
You can add new word(s) to dictionary in run-time
WordsNinja.addWords('Parsa'); // Add one word
WordsNinja.addWords(['Parsa', 'Kafi']); // Add one or more words
Example
let string = 'parsayouneedtolearnfromyourmistakes';
WordsNinja.addWords('Parsa');
let words = WordsNinja.splitSentence(string,
{
capitalizeFirstLetter: true, // Capitalize first letter of result
joinWords: true // Join words
}
);
console.log(words);
Result
Parsa You Need To Learn From Your Mistakes
I hope you find it useful :)
Top comments (0)