UNPKG

stringman

Version:

Stringman does string manipulation and other string operations. Do anything from lightening color codes to swapping email address in a string!

115 lines (114 loc) 3.42 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.words = void 0; const whitespace_1 = require("./whitespace"); const allWords = /\w+/g; const wordsSplitChars = /(\.|,|\?| |-|!)/gm; function specificWordCount(str, word, strict) { const strSplit = str.split(wordsSplitChars); const cleaned = strSplit.filter((t) => { return allWords.test(t); }); const counted = cleaned.filter((w) => { const num = !isNaN(parseFloat(w)); if (num) { return false; } else if (strict) { return word === w; } else { return word.toLowerCase() === w.toLowerCase(); } }); return counted ? counted.length : 0; } function wordCount(str) { const strSplit = str.split(wordsSplitChars); const cleaned = strSplit.filter((t) => { return allWords.test(t); }); if (cleaned && cleaned.length) { const counted = cleaned.filter((w) => { return isNaN(parseFloat(w)); }); return counted && counted.length ? counted.length : 0; } return 0; } function allWordCount(str, strict) { const strSplit = whitespace_1.whitespace .replaceWith(str, { tabs: true, breaks: true, multiSpace: true }, ' ') .split(wordsSplitChars); if (strSplit && strSplit.length) { const cleaned = strSplit.filter((t) => { return allWords.test(t); }); if (cleaned && cleaned.length) { return cleaned.reduce((acc, word) => { if (strict) { if (acc[word]) { acc[word] += 1; } else { acc[word] = 1; } } else { const lower = word.toLowerCase(); if (acc[lower]) { acc[lower] += 1; } else { acc[lower] = 1; } } return acc; }, {}); } else { return {}; } } else { return {}; } } function capitalize(str) { if (typeof str !== 'string') { return null; } return str.charAt(0).toUpperCase() + str.slice(1); } function replaceWord(str, word, replaceWith, cases) { if (typeof str !== 'string' || typeof word !== 'string' || typeof replaceWith !== 'string') { return null; } if (cases) { const regExp = new RegExp(word, 'gm'); const capWord = capitalize(word); const capRw = capitalize(replaceWith); const capExp = capWord ? new RegExp(capWord, 'gm') : null; const lc = str.replace(regExp, replaceWith); return capExp && capRw ? lc.replace(capExp, capRw) : null; } else { const insExp = new RegExp(word, 'gim'); return str.replace(insExp, replaceWith); } } function readingTime(wCount, imageCount, valueOnly = false, wordsPerMinute = 270) { if (valueOnly) { return Math.round(wCount / wordsPerMinute) + imageCount * 0.2; } return `${Math.round(wCount / wordsPerMinute) + imageCount * 0.2} min read`; } const words = { allWordCount, capitalize, replaceWord, specificWordCount, wordCount, readingTime }; exports.words = words;