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
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
- isIPv4 - Checks if a string is a valid IPv4 address
- isHexColor - Checks if the input string is a valid hex color
Analysis
- wordCount - Counts the number of words 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
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 |
✅ 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 |
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 |
📊 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'. |
🎨 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
Samarth Ruia |
John Cervantes |
Hardik Srivastav |
Ahmed Semih Erkan |
Michael van der Bend |
mamphis |
Stanisław Kumor |
Ali Medhat |
Soham Powar |
Abdul Arham |
💬 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