Package Exports
- stringzy
- stringzy/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (stringzy) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
A lightweight, zero-dependency NPM Package for elegant string manipulations. It provides a comprehensive range of text utilities for JavaScript and Node.js applications including transformations, validations, analysis, and formatting.
β¨ Features
- πͺ Powerful - Transform, validate, analyze, and format strings with minimal code
- πͺΆ Lightweight - Zero dependencies, tiny footprint
- π§© Modular - Import only what you need with organized namespaces
- π Fast - Optimized for performance
- β Tested - Reliable and robust
- π― Comprehensive - 4 specialized modules for all string needs
π¦ Installation
# Using npm
npm install stringzy
# Using yarn
yarn add stringzy
# Using pnpm
pnpm add stringzy
π Quick Start
// Import the entire library
import stringzy from 'stringzy';
// Or import specific functions
import { isEmail, wordCount, formatPhone } from 'stringzy';
// Or import by namespace
import { transform, validate, analyze, format } from 'stringzy';
// Transform your strings
const slug = stringzy.toSlug('Hello World!'); // 'hello-world'
const isValid = stringzy.validate.isEmail('user@example.com'); // true
const count = stringzy.analyze.wordCount('Hello world'); // 2
π Table of Contents
Transformations
- truncateText - Truncates text to a specified maximum length
- toSlug - Converts a string to a URL-friendly slug
- capitalizeWords - Capitalizes the first letter of each word
- removeSpecialChars - Removes special characters from a string
- removeWords - Removes specified words from a string
- removeDuplicates - Removes duplicate words from a string
- initials - Extracts initials from a text string
- camelCase - Converts the given string to Camel Case
- pascalCase - Converts the given string to Pascal Case
- snakeCase - Converts the given string to Snake Case
- kebabCase - Converts the given string to Kebab Case
- titleCase - Converts the given string to Title Case
- constantCase - Converts the given string to Constant Case
- escapeHTML - Escapes HTML special characters to prevent XSS attacks
- maskSegment - Masks a segment of a string by replacing characters between two indices with a specified character
- deburr β Removes accents and diacritical marks from a string
- splitChunks - Breaks a string down into chunks of specified length.
- numberToText - Converts a number to its text representation in specified language
- reverseWordsInString - Reverses the order of words in a given string
- stringPermutations - Generates all unique permutations of a given string.
- stringCombinations - Generates all unique combinations of a given string.
Validations
- isURL - Checks if a string is a valid URL
- isEmail - Checks if a string is a valid email address
- isDate - Checks if a string is a valid date
- isEmpty - Checks if a string is empty or contains only whitespace
- isSlug - Checks if a string is a valid slug
- isTypeOf - Checks if a file or URL has a valid extension for a given type
- isIPv4 - Checks if a string is a valid IPv4 address
- isHexColor - Checks if the input string is a valid hex color
- isPalindrome - Checks if the input string is a palindrome (ignores case, spaces, and punctuation)
- isCoordinates - Checks if given latitude and longitude are valid coordinates
- isLowerCase - Checks if given string only has lower case characters.
- isUpperCase - Checks if given string only has upper case characters.
- isAlphabetic - Checks if input string contains only Alphabets (case insensitive)
- isAlphaNumeric - Checks if input string contains only Alphabets and Digits (case insensitive)
- isAnagram- Checks if both strings are anagrams of each other. (ignores case and punctuations)
- isMacAddress- Checks if a given string is a valid MAC address.
- isPanagram- Checks if a given string is a pangram (contains every letter of the English alphabet at least once).
Analysis
- wordCount - Counts the number of words in a string
- contentWordCount- Counts the number of content words (nouns, verbs, adjectives, adverbs, etc.) in a string.
- functionWordCount- Counts the number of function words (prepositions, pronouns, conjunctions, articles, etc.) in a string.
- readingDuration - Calculates the reading duration of a given string
- characterCount - Counts the number of characters in a string
- characterFrequency - Analyzes character frequency in a string
- stringSimilarity - Calculates the percentage similarity between two strings
- complexity - Analyzes string complexity including score, uniqueness, and length
- patternCount - calculates the number of times a specific pattern occurs in a given text
- vowelConsonantCount - Counts the number of vowels and consonants in a given string
- checkMultiplePatterns - Finds occurrences of multiple patterns within a given text using RabinβKarp algorithm (case sensitive)
- checkSubsequence - Checks whether the second string is a subsequence of the first string (case sensitive)
- stringRotation - Checks if one string is a rotation of another (case sensitive).
Formatting
- capitalize - Capitalizes the first letter of each word
- formatNumber - Formats a number string with thousand separators
- formatPhone - Formats a phone number string to standard format
π API Reference
π Transformations
Functions for transforming and manipulating strings.
truncateText(text, maxLength, suffix = '...')
Truncates text to a specified maximum length, adding a suffix if truncated.
import { truncateText } from 'stringzy';
truncateText('This is a long sentence that needs truncating', 10);
// Returns: 'This is a...'
truncateText('This is a long sentence', 10, ' β');
// Returns: 'This is a β'
truncateText('Short', 10);
// Returns: 'Short' (no truncation needed)
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to truncate |
maxLength | number | required | Maximum length of the output string (excluding suffix) |
suffix | string | '...' | String to append if truncation occurs |
toSlug(text)
Converts a string to a URL-friendly slug.
import { toSlug } from 'stringzy';
toSlug('Hello World!');
// Returns: 'hello-world'
toSlug('This is a TEST string 123');
// Returns: 'this-is-a-test-string-123'
toSlug('Special $#@! characters');
// Returns: 'special-characters'
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to convert to a slug |
capitalizeWords(text)
Capitalizes the first letter of each word in a string.
import { capitalizeWords } from 'stringzy';
capitalizeWords('hello world');
// Returns: 'Hello World'
capitalizeWords('javascript string manipulation');
// Returns: 'Javascript String Manipulation'
capitalizeWords('already Capitalized');
// Returns: 'Already Capitalized'
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to capitalize |
removeSpecialChars(text, replacement = '')
Removes special characters from a string, optionally replacing them.
import { removeSpecialChars } from 'stringzy';
removeSpecialChars('Hello, world!');
// Returns: 'Hello world'
removeSpecialChars('email@example.com');
// Returns: 'emailexamplecom'
removeSpecialChars('Phone: (123) 456-7890', '-');
// Returns: 'Phone-123-456-7890'
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to process |
replacement | string | '' | String to replace special characters with |
removeWords(text, wordsToRemove)
Removes specified words from a string
import { removeWords } from 'stringzy';
removeWords('Hello world this is a test', ['this', 'is']);
// Returns: 'Hello world a test'
removeWords('Remove The Quick BROWN fox', ['the', 'brown']);
// Returns: 'Remove Quick fox'
removeWords('JavaScript is awesome and JavaScript rocks', ['JavaScript']);
// Returns: 'is awesome and rocks'
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to process |
wordsToRemove | string[] | required | Array of words to remove from the string |
removeDuplicates(text)
Removes duplicate case-sensitive words from a given text.
import { removeDuplicates } from 'stringzy';
removeDuplicates('Hello world this is a is a test');
// Returns: 'Hello world this is a test'
removeDuplicates('Remove me me me me or Me');
// Returns: 'Remove me or Me'
removeDuplicates('JavaScript is not bad and not awesome');
// Returns: 'JavaScript is not bad and awesome'
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to process |
initials(text, limit)
Extracts initials from a text string.
import { initials } from 'stringzy';
initials('John Doe');
// Returns: 'JD'
initials('Alice Bob Charlie', 2);
// Returns: 'AB'
initials('Hello World Test Case');
// Returns: 'HWTC'
initials('single');
// Returns: 's'
initials(' Multiple Spaces Between ');
// Returns: 'MSB'
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to extract initials from |
limit | number | undefined | Maximum number of initials to return (optional) |
camelCase(text)
Converts the given string to Camel Case.
import { camelCase } from 'stringzy';
camelCase('hello world'); // 'helloWorld'
camelCase('this is a test'); // 'thisIsATest'
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to convert to Camel Case |
pascalCase(text)
Converts the given string to Pascal Case.
import { pascalCase } from 'stringzy';
pascalCase('hello world'); // 'HelloWorld'
pascalCase('this is a test'); // 'ThisIsATest'
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to convert to Pascal Case |
snakeCase(text)
Converts the given string to Snake Case.
import { snakeCase } from 'stringzy';
snakeCase('hello world'); // 'hello_world'
snakeCase('this is a test'); // 'this_is_a_test'
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to convert to Snake Case |
kebabCase(text)
Converts the given string to Kebab Case.
import { kebabCase } from 'stringzy';
kebabCase('hello world'); // 'hello-world'
kebabCase('this is a test'); // 'this-is-a-test'
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to convert to Kebab Case |
titleCase(text)
Converts the given string to Title Case.
import { titleCase } from 'stringzy';
titleCase('hello world'); // 'Hello World'
titleCase('this is a test'); // 'This Is A Test'
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to convert to Title Case |
constantCase(text)
Converts the given string to Constant Case.
import { constantCase } from 'stringzy';
constantCase('hello world'); // 'HELLO_WORLD'
constantCase('this is a test'); // 'THIS_IS_A_TEST'
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to convert to Constant Case |
escapeHTML(text)
Escapes HTML special characters to prevent XSS attacks by converting them to their HTML entities.
import { escapeHTML } from 'stringzy';
escapeHTML('Tom & Jerry');
// Returns: 'Tom & Jerry'
escapeHTML('<script>alert("XSS")</script>');
// Returns: '<script>alert("XSS")</script>'
escapeHTML('<div class="test">content</div>');
// Returns: '<div class="test">content</div>'
escapeHTML('Say "Hello" & it\'s < 5 > 2');
// Returns: 'Say "Hello" & it's < 5 > 2'
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to escape HTML characters from |
maskSegment(text, maskStart, maskEnd, maskChar?)
Masks a segment of a string by replacing characters between two indices with a specified character (default is '*').
import { maskSegment } from 'stringzy';
maskSegment('1234567890', 2, 6);
// Returns: '12****7890'
maskSegment('abcdef', 1, 4, '#');
// Returns: 'a###ef'
maskSegment('token');
// Returns: '*****'
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to apply the masking to |
maskStart | number | 0 |
The start index (inclusive) of the segment to mask |
maskEnd | number | text.length |
The end index (exclusive) of the segment to mask |
maskChar | string | '*' |
The character to use for masking (must be one character) |
deburr(text)
Removes accents and diacritics from letters in a string (e.g. dΓ©jΓ vu β deja vu).
import { deburr } from 'stringzy';
deburr('dΓ©jΓ vu');
// Returns: 'deja vu'
deburr('ΓlΓ¨ve SΓ£o Paulo');
// Returns: 'Eleve Sao Paulo'
deburr('ΓΌber cool');
// Returns: 'uber cool'
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to strip diacritics from |
splitChunks(text, chunkSize)
Takes a string and chunk size as the argument and splits the string into chunks of given size.
import { splitChunks } from 'stringzy';
splitChunks('helloworld', 2);
// Returns: ['he', 'll', 'ow', 'or', 'ld']
splitChunks('helloworld', 3);
// Returns: ['hel', 'low', 'orl', 'd']
splitChunks('helloworld');
// Returns: ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string that needs to be chunked |
chunkSize | number | 1 |
The size of each chunk in which the string is to be split |
numberToText(num, lang)
Converts a number to its text representation in the specified language.
import { numberToText } from 'stringzy';
numberToText(12345); // Returns: 'twelve thousand three hundred forty-five'
numberToText(12345, 'en'); // Returns: 'twelve thousand three hundred forty-five'
numberToText(12345, 'pl'); // Returns: 'dwanaΕcie tysiΔcy trzysta czterdzieΕci piΔΔ'
Parameter | Type | Default | Description |
---|---|---|---|
num | number | required | The number to convert to text |
lang | string | 'en' | The language code for the text representation (e.g., 'en' for English, 'pl' for Polish) |
Available languages: en (English), pl (Polish).
reverseWordsInString(str)
Reverses the order of words in a string and reverses the position of surrounding whitespace (leading becomes trailing and vice-versa). Reverses the order of words in a string while preserving the exact original spacing between each word.
import { reverseWordsInString } from 'stringzy';
reverseWordsInString('Hello world from stringzy');
// Returns: 'stringzy from world Hello'
// Note how the double and triple spaces are preserved:
reverseWordsInString(' leading spaces and trailing ');
// Returns: ' trailing and spaces leading '
reverseWordsInString('single-word');
// Returns: 'single-word'
Parameter | Type | Default | Description |
---|---|---|---|
str | string | required | The input string to reverse |
stringPermutations(str)
Generates all unique permutations of a given string. Repeated characters are handled by ensuring only unique permutations are included in the output array. The order of permutations is not guaranteed.
stringPermutations('ab');
// ['ab', 'ba']
stringPermutations('abc');
// ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
stringPermutations('aab');
// ['aab', 'aba', 'baa']
stringPermutations('');
// ['']
stringPermutations('a');
// ['a']
stringPermutations('a1!');
// ['a1!', 'a!1', '1a!', '1!a', '!a1', '!1a']
Parameter | Type | Default | Description |
---|---|---|---|
str | string | required | The input string to generate all unique permutations. |
stringCombinations(str)
Generates all unique combinations (subsequences) of a given string, including the empty string.
Duplicate characters are handled by ensuring only unique combinations are returned.
The order of combinations in the output array is not guaranteed.
stringCombinations('ab');
// ["", "a", "b", "ab"]
stringCombinations('abc');
// ["", "a", "b", "c", "ab", "ac", "bc", "abc"]
stringCombinations('aab');
// ["", "a", "b", "aa", "ab", "aab"]
stringCombinations('');
// [""]
stringCombinations('A');
// ["", "A"]
stringCombinations('!@');
// ["", "!", "@", "!@"]
Parameter | Type | Default | Description |
---|---|---|---|
str | string | required | The input string to generate unique combinations from. |
β Validations
Functions for validating string formats and content.
isURL(text)
Checks if a string is a valid URL.
isURL('https://example.com'); // true
isURL('not-a-url'); // false
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to validate as URL |
isEmail(text)
Checks if a string is a valid email address.
isEmail('user@example.com'); // true
isEmail('invalid-email'); // false
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to validate as email |
isDate(text)
Checks if a string is a valid date.
import { isDate } from 'stringzy';
isDate('2023-12-25', DateFormat.YYYMMDD); // true
isDate('12/25/2023', DateFormat.MMDDYYY, '/'); // true
isDate('20-12-25', DateFormat.YYYMMDD); // false
isDate('2023-12-1', DateFormat.YYYMMDD); // false
isDate('invalid-date', DateFormat.YYYMMDD); // false
isDate('2023-13-45', DateFormat.YYYMMDD); // false
Parameter | Type | Default | Description |
---|---|---|---|
input | string | required | The input string to validate as date |
format | DateFormats | required | The date format to validate against |
separator | string | optional | The separator to be used if it is not "-" |
isEmpty(text)
Checks if a string is empty or contains only whitespace.
isEmpty(' '); // true
isEmpty('hello'); // false
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to check for emptiness |
isSlug(text)
Checks if a string is a valid slug.
isSlug('hello-world'); // true
isSlug('test-product-123'); // true
isSlug('Hello-World'); // false (uppercase letters)
isSlug('hello--world'); // false (consecutive hyphens)
isSlug('-hello-world'); // false (starts with hyphen)
isSlug('hello_world'); // false (underscore not allowed)
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to validate as slug |
isTypeOf(input, type)
Checks if a file or URL has a valid extension for a given type
isType('photo.PNG', 'image'); // true
isType('https://example.com/logo.svg', 'image'); // true
isType({ name: 'track.mp3' }, 'audio'); // true
isType('filewithoutextension', 'image'); // false
isType('document.zip', 'document'); // false
isType('video.mp4', 'document'); // false
Parameter | Type | Default | Description |
---|---|---|---|
input | string | required | The file name, URL string, or object with .name |
input | string | required | The file type category to validate (image, video, audio, document, archive) |
isIPv4(text)
Checks if a string is a valid IPv4 address.
import { isIPv4 } from 'stringzy';
isIPv4('192.168.1.1'); // true
isIPv4('0.0.0.0'); // true
isIPv4('256.1.1.1'); // false (out of range)
isIPv4('192.168.1'); // false (incomplete)
isIPv4('192.168.01.1'); // false (leading zeros)
isIPv4('192.168.1.a'); // false (non-numeric)
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to validate as IPv4 address |
isHexColor(text)
Checks if a string is a valid Hex color.
import { isHexColor } from 'stringzy';
isHexColor('#fff'); // true
isHexColor('fff'); // true
isHexColor('#a1b2c3'); // true
isHexColor('123abc'); // true
isHexColor('#1234'); // false
isHexColor('blue'); // false
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to validate as Hex color |
isPalindrome(text)
Checks if a string is a palindrome. The check is case-insensitive and ignores spaces and punctuation.
import { isPalindrome } from 'stringzy';
isPalindrome('racecar'); // true
isPalindrome('A man, a plan, a canal: Panama'); // true
isPalindrome('No lemon, no melon'); // true
isPalindrome('hello'); // false
isPalindrome('Was it a car or a cat I saw?'); // true
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to check for palindrome |
isCoordinates(latitude, longitude)
Checks if given latitude and longitude are valid coordinates.
import { isCoordinates } from 'stringzy';
isCoordinates(48.8582, 2.2945); // true
isCoordinates(40.748817, -73.985428); // true
isCoordinates(9999, -9999); // false
Parameter | Type | Default | Description |
---|---|---|---|
latitude | number | required | Latitude to validate |
longitude | number | required | Longitude to validate |
isLowerCase(str)
Checks whether the given string contains only lowercase alphabetic characters. Ignores digits, special characters, white spaces.
import { isLowerCase } from 'stringzy';
isLowerCase('hello'); // true
isLowerCase('hello123!'); // true
isLowerCase('Hello'); // false
isLowerCase('12345'); // false
Parameter | Type | Default | Description |
---|---|---|---|
str | string | required | The input string to validate as containing lowercase alphabetic letters |
isUpperCase(str)
Checks whether the given string contains only uppercase alphabetic characters. Ignores digits, special characters, white spaces.
import { isUpperCase } from 'stringzy';
isUpperCase('HELLO'); // true
isUpperCase('HELLO123!'); // true
isUpperCase('Hello'); // false
isUpperCase('12345'); // false
Parameter | Type | Default | Description |
---|---|---|---|
str | string | required | The input string to validate as containing uppercase alphabetic letters |
isAlphabetic(text)
Checks if a string contains only alphabetic characters (a-z, A-Z). Throws an error if the input is not a string.
import { isAlphabetic } from 'stringzy';
isAlphabetic('hello'); // true
isAlphabetic('World'); // true
isAlphabetic('helloWORLD'); // true
isAlphabetic('abc123'); // false
isAlphabetic('hello!'); // false
isAlphabetic(''); // false
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to check for alphabetic only |
isAlphaNumeric(text)
Checks if a string contains only alphanumeric characters (letters and digits). Throws an error if the input is not a string.
import { isAlphaNumeric } from 'stringzy';
isAlphaNumeric('abc123'); // true
isAlphaNumeric('A1B2C3'); // true
isAlphaNumeric('123'); // true
isAlphaNumeric('hello'); // true
isAlphaNumeric('hello!'); // false
isAlphaNumeric('123 456'); // false
isAlphaNumeric(''); // false
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to check for alphanumeric only |
isAnagram(str1, str2)
Checks whether two strings are anagrams of each other (contain the same characters in the same frequency, regardless of order).
- Comparison is case-insensitive.
- Spaces and punctuation are ignored.
- Throws an error if either input is not a string.
import { isAnagram } from 'stringzy';
isAnagram('listen', 'silent'); // true
isAnagram('Debit Card', 'Bad Credit'); // true
isAnagram('Astronomer', 'Moon starer'); // true
isAnagram('hello', 'world'); // false
isAnagram('a', 'b'); // false
isAnagram('', ''); // true
Parameter | Type | Default | Description |
---|---|---|---|
str1 | string | required | The first string to check as an anagram |
str2 | string | required | The second string to check as an anagram |
isMacAddress(str)
Checks whether a given string is a valid MAC address.
- A valid MAC address consists of six pairs of hexadecimal digits (
0β9
,AβF
, case-insensitive). - Returns
true
if the string is a valid MAC address, otherwisefalse
. - Throws an error if input is not a string.
import { isMacAddress } from 'stringzy';
isMacAddress("00:1A:2B:3C:4D:5E"); // true
isMacAddress("00-1A-2B-3C-4D-5E"); // true
isMacAddress("aa:bb:cc:dd:ee:ff"); // true
isMacAddress("FF-FF-FF-FF-FF-FF"); // true
isMacAddress("00:1G:2B:3C:4D:5E"); // false (invalid hex digit)
isMacAddress("00:1A-2B:3C-4D:5E"); // false (mixed separators)
isMacAddress("001A:2B:3C:4D:5E"); // false (wrong group length)
isMacAddress("hello-world-mac"); // false (invalid format)
isMacAddress(""); // false (empty string)
Parameter | Type | Default | Description |
---|---|---|---|
str | string | required | The string to validate as a MAC address |
isPangram(str)
- Checks if a given string is a pangram (i.e., contains every letter of the English alphabet at least once).
- The check is case-insensitive, and non-alphabetic characters (numbers, punctuation, spaces) are ignored. An empty string is not considered a pangram.
- Throws an error if the input is not a string.
import { isPangram } from 'stringzy';
isPangram("The quick brown fox jumps over the lazy dog."); // true
isPangram("This is not a pangram."); // false
isPangram("Abcdefghijklmnopqrstuvwxyz"); // true
isPangram("AbCdEfGhIjKlMnOpQrStUvWxYz"); // true
isPangram("A-B-C-D-E-F-G-H-I-J-K-L-M-N-O-P-Q-R-S-T-U-V-W-X-Y-Z"); // true
isPangram(""); // false
isPangram("Hello world"); // false
Parameter | Type | Default | Description |
---|---|---|---|
str | string | required | The input string to check for pangram characteristics |
π Analysis
Functions for analyzing string content and structure.
readingDuration(text, readingSpeed = 230)
Calculates the estimated reading duration for a given text based on an average reading speed.
import { readingDuration } from 'stringzy';
readingDuration(
'This is a sample text with twenty-three words to test the reading duration function.'
);
// Returns: 0 (23 words / 230 words per minute β 0 minutes)
readingDuration(
'This text contains fifty words. It is designed to test the reading duration function with a larger input.',
200
);
// Returns: 1 (50 words / 200 words per minute β 1 minute)
readingDuration(Array(9999).fill('Word').join(' '));
// Returns: 43 (9999 words / 230 words per minute β 43 minutes)
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input text for which the reading duration is to be calculated |
readingSpeed | number | 230 | The reading speed in words per minute. Defaults to 230 (average reading speed) |
wordCount(text)
Counts the number of words in a string.
wordCount('Hello world'); // 2
wordCount(''); // 0
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to count words in |
characterCount(text)
Counts the number of characters in a string.
characterCount('Hello'); // 5
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to count characters in |
characterFrequency(text)
Analyzes character frequency in a string (excluding spaces).
characterFrequency('hello'); // { h: 1, e: 1, l: 2, o: 1 }
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to analyze character frequency |
stringSimilarity(textA, textB, algorithm = 'Levenshtein')
Calculates the percentage similarity between two texts using the selected algorithm. Method returns a percentage (0β100) value indicating how similar the two strings are.
stringSimilarity('kitten', 'sitting'); // Returns: 57.14
stringSimilarity('hello', 'hello'); // Returns: 100
stringSimilarity('flaw', 'lawn', 'Damerau-Levenshtein'); // Returns: 50
Parameter | Type | Default | Description |
---|---|---|---|
textA | string | required | The first text to compare. |
textB | string | required | The second text to compare. |
algorithm | string | 'Levenshtein' | The algorithm to use: 'Levenshtein' or 'Damerau-Levenshtein'. |
complexity(text)
Analyzes the complexity of a string, returning an object with detailed metrics.
import { complexity } from 'stringzy';
complexity('abc');
// Returns: { score: [number], uniqueness: [number], length: 3 }
complexity('aA1!aA1!');
// Returns: { score: [number], uniqueness: [number], length: 8 }
complexity('');
// Returns: { score: 0, uniqueness: 0, length: 0 }
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to analyze complexity |
Returns: An object containing:
score
(number): Overall complexity scoreuniqueness
(number): Measure of character uniquenesslength
(number): Length of the input string
feature/content-words
contentWordCount(text)
Counts the number of content words (nouns, verbs, adjectives, adverbs, etc.) in a string.
import { contentWordCount } from 'stringzy';
contentWordCount("Learning JavaScript improves coding skills!");
// Returns: { count: 5 }
contentWordCount("The cat sleeps on the warm windowsill.");
// Returns: { count: 5 }
contentWordCount("Wow! Such a beautiful day.");
// Returns: { count: 4 }
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to analyze content words |
Returns: An object containing:
count
(number): Total number of content words in the string
functionWordCount(text)
Counts the number of function words (prepositions, pronouns, conjunctions, articles, etc.) in a string.
import { functionWordCount } from 'stringzy';
functionWordCount("She and I are going to the park.");
// Returns: { count: 7 }
functionWordCount("It is an example of proper grammar usage.");
// Returns: { count: 8 }
functionWordCount("Can you see the stars tonight?");
// Returns: { count: 5 }
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to analyze function words |
Returns: An object containing:
count
(number): Total number of function words in the string
patternCount(text, pattern)
Counts the number of times a substring (pattern) occurs in a string, including overlapping occurrences.
This function uses the KnuthβMorrisβPratt (KMP) algorithm for efficient matching.
patternCount('aaaa', 'aa'); // 3
patternCount('abababa', 'aba'); // 3
patternCount('hello world', 'o'); // 2
patternCount('hello world', 'x'); // 0
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to search in |
pattern | string | required | The substring (pattern) to count (overlapping) |
vowelConsonantCount(str)
Counts the number of vowels and consonants in a given string.
This function is case-insensitive and ignores non-alphabetic characters.
vowelConsonantCount('hello');
// { vowels: 2, consonants: 3 }
vowelConsonantCount('stringzy');
// { vowels: 1, consonants: 7 }
vowelConsonantCount('');
// { vowels: 0, consonants: 0 }
Parameter | Type | Default | Description |
---|---|---|---|
str | string | required | The input string to count vowels and consonants in |
feature/content-words
checkMultiplePatterns(text, patterns)
Finds occurrences of multiple patterns within a given text using the RabinβKarp algorithm.
Accepts an array of patterns.
Returns all matches of each pattern along with starting indices.
Handles hash collisions by verifying actual substrings.
Pattern matching is case sensitive.
checkMultiplePatterns('abracadabra', ['abra', 'cad']);
// { abra: [0, 7], cad: [4] }
checkMultiplePatterns('aaaa', ['aa', 'aaa']);
// { aa: [0, 1, 2], aaa: [0, 1] }
checkMultiplePatterns('hello world', ['xyz', '123']);
// { xyz: [], 123: [] }
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The text to search within. |
patterns | string[ ] | required | An array of patterns to search for (each must be a string). |
checkSubsequence(str, sub)
Checks whether a given string sub is a subsequence of another string str. A subsequence maintains the relative order of characters, but they do not need to be consecutive. Case-sensitive comparison is performed. Spaces and all characters are treated literally.
isSubsequence('abcde', 'ace');
// true β 'a', 'c', 'e' appear in order
isSubsequence('abracadabra', 'aaa');
// true β multiple 'a's in correct order
isSubsequence('abcde', 'aec');
// false β order is broken (e comes before c)
isSubsequence('anything', '');
// true β empty subsequence is always valid
isSubsequence('AbC', 'AC');
// true β exact case matches
isSubsequence('a b c', 'abc');
// false β spaces count as characters
Parameter | Type | Default | Description |
---|---|---|---|
str | string | required | The main string to check within. |
sub | string | required | The subsequence string to verify against str . |
checkStringRotations(str1, str2)
Checks whether a given string str2
is a rotation of another string str1
.
Case-sensitive comparison is performed. Both strings must be of equal length to be considered rotations.
Spaces and all characters are treated literally.
isRotation('waterbottle', 'erbottlewat');
// true β rotation at position 3
isRotation('abcde', 'cdeab');
// true β rotation at position 2
isRotation('abc', 'abc');
// true β no rotation, identical strings
isRotation('abc', 'cab');
// true β rotation at position 2
isRotation('abc', 'bac');
// false β not a valid rotation
isRotation('ArB', 'Bar');
// false β case-sensitive mismatch
isRotation('abcd', 'abc');
// false β lengths differ
Parameter | Type | Default | Description |
---|---|---|---|
str1 | string | required | The original string. |
str2 | string | required | The string to verify if it is a rotation of str1 . |
π¨ Formatting
Functions for formatting strings into specific patterns.
capitalize(text)
Capitalizes the first letter of each word.
capitalize('hello world'); // 'Hello World'
capitalize('javaScript programming'); // 'Javascript Programming'
Parameter | Type | Default | Description |
---|---|---|---|
text | string | required | The input string to capitalize |
formatNumber(number, separator = ',')
Formats a number string with thousand separators.
formatNumber('1234567'); // '1,234,567'
formatNumber('1234567', '.'); // '1.234.567'
Parameter | Type | Default | Description |
---|---|---|---|
number | string|number | required | The number to format |
separator | string | ',' | The separator to use for thousands |
formatPhone(phone, format = 'us')
Formats a phone number string to standard format.
formatPhone('1234567890'); // '(123) 456-7890'
formatPhone('11234567890', 'international'); // '+1 (123) 456-7890'
Parameter | Type | Default | Description |
---|---|---|---|
phone | string | required | The phone number string to format |
format | string | 'us' | Format type: 'us' or 'international' |
π§ Usage Patterns
Individual Function Imports
import { isEmail, wordCount, capitalize } from 'stringzy';
const email = 'user@example.com';
if (isEmail(email)) {
console.log('Valid email!');
}
Namespace Imports
import { validate, analyze, format } from 'stringzy';
// Organized by functionality
const emailValid = validate.isEmail('test@example.com');
const words = analyze.wordCount('Hello world');
const formatted = format.capitalize('hello world');
Default Import (All Functions)
import stringzy from 'stringzy';
// Access any function
stringzy.toUpperCase('hello');
stringzy.validate.isEmail('test@example.com');
stringzy.analyze.wordCount('Hello world');
stringzy.format.capitalize('hello world');
π οΈ Usage Examples
In a React component
import React from 'react';
import { truncateText, capitalize, wordCount, isEmpty } from 'stringzy';
function ArticlePreview({ title, content }) {
const displayTitle = isEmpty(title) ? 'Untitled' : capitalize(title);
const previewText = truncateText(content, 150);
const readingTime = Math.ceil(wordCount(content) / 200);
return (
<div className="article-preview">
<h2>{displayTitle}</h2>
<p>{previewText}</p>
<small>{readingTime} min read</small>
</div>
);
}
Form Validation
import { validate } from 'stringzy';
function validateForm(formData) {
const errors = {};
if (!validate.isEmail(formData.email)) {
errors.email = 'Please enter a valid email address';
}
if (!validate.isURL(formData.website)) {
errors.website = 'Please enter a valid URL';
}
if (validate.isEmpty(formData.name)) {
errors.name = 'Name is required';
}
return errors;
}
Content Analysis Dashboard
import { analyze } from 'stringzy';
function getContentStats(text) {
return {
words: analyze.wordCount(text),
characters: analyze.characterCount(text),
frequency: analyze.characterFrequency(text),
readingTime: Math.ceil(analyze.wordCount(text) / 200),
};
}
Data Formatting
import { format } from 'stringzy';
function formatUserData(userData) {
return {
name: format.capitalize(userData.name),
phone: format.formatPhone(userData.phone),
revenue: format.formatNumber(userData.revenue),
};
}
π TypeScript Support
The package includes TypeScript type definitions for all functions.
import { validate, analyze, format } from 'stringzy';
// TypeScript will provide proper type checking
const isValid: boolean = validate.isEmail('test@example.com');
const count: number = analyze.wordCount('Hello world');
const formatted: string = format.capitalize('hello world');
ποΈ Architecture
stringzy is organized into four specialized modules:
transformations.js
- Core string transformationsvalidations.js
- String validation utilitiesanalysis.js
- String analysis and metricsformatting.js
- String formatting functions
Each module can be imported individually or accessed through the main entry point.
π€ Contributing
Contributions are welcome! Please read our contribution guidelines before submitting a pull request.
Contributors
π¬ Join the Community
Have questions, ideas, or want to contribute? Join our Discord server to chat with the community, discuss features, and help shape the future of the project.
π License
This project is licensed under the MIT License - see the LICENSE file for details.
π Acknowledgments
- Thank you to all contributors and users of this package!
- Inspired by the need for comprehensive yet simple string manipulation utilities.
If you have contributed to this project and your image is not here, please let us know, and we'll be happy to add it!
Made with β€οΈ by Samarth Ruia