Overview
StringUtils provides a comprehensive set of string manipulation methods for common operations like slugification, capitalization, case conversion, truncation, masking, and more. All methods handle null/undefined inputs safely.
Import
import { StringUtils } from '@bytekit/utils/helpers';
Methods
removeDiacritics
Removes diacritics (accent marks) from a string.
value
string | null | undefined
The input string to process
Returns: string - String with diacritics removed
StringUtils.removeDiacritics('café');
// Returns: 'cafe'
StringUtils.removeDiacritics('Héllö Wörld');
// Returns: 'Hello World'
StringUtils.removeDiacritics(null);
// Returns: ''
slugify
Converts a string to a URL-friendly slug.
value
string | null | undefined
The input string to slugify
Optional configuration objectCharacter to use as separator
Returns: string - URL-friendly slug
StringUtils.slugify('Hello World!');
// Returns: 'hello-world'
StringUtils.slugify('Product Name 2024', { separator: '_' });
// Returns: 'product_name_2024'
StringUtils.slugify('Café Münchën', { lowercase: false });
// Returns: 'Cafe-Munchen'
Edge Cases:
- Removes diacritics automatically
- Trims leading/trailing separators
- Collapses multiple separators into one
compactWhitespace
Replaces multiple whitespace characters with a single space and trims edges.
value
string | null | undefined
The input string to compact
Returns: string - Compacted string
StringUtils.compactWhitespace(' Hello World \n\t Test ');
// Returns: 'Hello World Test'
StringUtils.compactWhitespace('Multiple spaces');
// Returns: 'Multiple spaces'
capitalize
Capitalizes the first character and lowercases the rest.
value
string | null | undefined
The input string to capitalize
Locale for case conversion
Returns: string - Capitalized string
StringUtils.capitalize('hello world');
// Returns: 'Hello world'
StringUtils.capitalize('HELLO');
// Returns: 'Hello'
StringUtils.capitalize('istanbul', 'tr-TR');
// Returns: 'İstanbul' (Turkish locale)
capitalizeWords
Capitalizes the first character of each word.
value
string | null | undefined
The input string to process
Locale for case conversion
Returns: string - String with capitalized words
StringUtils.capitalizeWords('hello world');
// Returns: 'Hello World'
StringUtils.capitalizeWords('the quick brown fox');
// Returns: 'The Quick Brown Fox'
truncate
Truncates a string to a maximum length with ellipsis.
value
string | null | undefined
The input string to truncate
Maximum length including ellipsis
Optional configuration objectString to append when truncated
Avoid cutting words in the middle
Returns: string - Truncated string
StringUtils.truncate('This is a long text', 10);
// Returns: 'This is…'
StringUtils.truncate('Hello world', 8, { ellipsis: '...' });
// Returns: 'Hello...'
StringUtils.truncate('Word boundaries test', 15, {
respectWordBoundaries: false
});
// Returns: 'Word boundari…'
Validation:
- Returns original string if it’s shorter than maxLength
- Always reserves space for ellipsis in the count
mask
Masks part of a string for privacy (e.g., credit cards, emails).
value
string | null | undefined
The input string to mask
Optional configuration objectCharacter to use for masking
Number of characters visible at start
Number of characters visible at end
Returns: string - Masked string
StringUtils.mask('1234567890');
// Returns: '••••••7890'
StringUtils.mask('user@example.com', {
visibleStart: 2,
visibleEnd: 10
});
// Returns: 'us••xample.com'
StringUtils.mask('secret', { maskChar: '*', visibleEnd: 2 });
// Returns: '****et'
Edge Cases:
- Returns original string if visibleStart + visibleEnd >= length
- Returns empty string for null/undefined input
interpolate
Replaces placeholders in a template string with values.
Template string with syntax
params
Record<string, unknown>
required
Object containing values for placeholders
Optional configuration objectThrow error for missing values
Value to use when key is missing
transform
(value: unknown, key: string) => string
Function to transform values before interpolation
Returns: string - Interpolated string
StringUtils.interpolate('Hello {{name}}!', { name: 'Alice' });
// Returns: 'Hello Alice!'
StringUtils.interpolate('{{user.name}} has {{user.points}} points', {
user: { name: 'Bob', points: 100 }
});
// Returns: 'Bob has 100 points'
StringUtils.interpolate('Value: {{missing}}', {}, { fallback: 'N/A' });
// Returns: 'Value: N/A'
StringUtils.interpolate('{{price}}',
{ price: 19.99 },
{ transform: (v) => `$${v}` }
);
// Returns: '$19.99'
Features:
- Supports nested paths:
{{user.profile.name}}
- Supports array indices:
{{items[0]}}
- Throws error in strict mode for missing keys
initials
Extracts initials from a name or phrase.
value
string | null | undefined
The input string to extract initials from
Optional configuration objectMaximum number of initials to extract
Convert initials to uppercase
Returns: string - Extracted initials
StringUtils.initials('John Doe');
// Returns: 'JD'
StringUtils.initials('Alice Bob Charlie', { limit: 3 });
// Returns: 'ABC'
StringUtils.initials('jane smith', { uppercase: false });
// Returns: 'js'
toQueryString
Converts an object to a URL query string.
params
Record<string, unknown> | null | undefined
Object to convert to query string
Optional configuration objectarrayFormat
'repeat' | 'bracket' | 'comma'
default:"repeat"
Format for array serialization
URL encode keys and values
Returns: string - URL query string
StringUtils.toQueryString({ name: 'Alice', age: 30 });
// Returns: 'age=30&name=Alice'
StringUtils.toQueryString({ tags: ['red', 'blue'] });
// Returns: 'tags=red&tags=blue'
StringUtils.toQueryString({ tags: ['red', 'blue'] }, {
arrayFormat: 'bracket'
});
// Returns: 'tags[]=red&tags[]=blue'
StringUtils.toQueryString({ ids: [1, 2, 3] }, {
arrayFormat: 'comma'
});
// Returns: 'ids=1,2,3'
StringUtils.toQueryString({
user: { name: 'Bob', active: true }
});
// Returns: 'user[active]=true&user[name]=Bob'
Features:
- Handles nested objects
- Multiple array formats
- Automatic Date serialization to ISO string
- Boolean serialization to ‘true’/‘false’
camelCase
Converts a string to camelCase.
value
string | null | undefined
The input string to convert
Returns: string - camelCase string
StringUtils.camelCase('hello world');
// Returns: 'helloWorld'
StringUtils.camelCase('user-name-field');
// Returns: 'userNameField'
StringUtils.camelCase('PascalCaseString');
// Returns: 'pascalCaseString'
pascalCase
Converts a string to PascalCase.
value
string | null | undefined
The input string to convert
Returns: string - PascalCase string
StringUtils.pascalCase('hello world');
// Returns: 'HelloWorld'
StringUtils.pascalCase('user-profile-component');
// Returns: 'UserProfileComponent'
StringUtils.pascalCase('camelCaseString');
// Returns: 'CamelCaseString'
kebabCase
Converts a string to kebab-case.
value
string | null | undefined
The input string to convert
Returns: string - kebab-case string
StringUtils.kebabCase('Hello World');
// Returns: 'hello-world'
StringUtils.kebabCase('userProfileName');
// Returns: 'user-profile-name'
StringUtils.kebabCase('PascalCase123Test');
// Returns: 'pascal-case-123-test'
snakeCase
Converts a string to snake_case.
value
string | null | undefined
The input string to convert
Returns: string - snake_case string
StringUtils.snakeCase('Hello World');
// Returns: 'hello_world'
StringUtils.snakeCase('userProfileName');
// Returns: 'user_profile_name'
StringUtils.snakeCase('CamelCase123Test');
// Returns: 'camel_case_123_test'
Type Definitions
interface SlugifyOptions {
separator?: string;
lowercase?: boolean;
}
interface TruncateOptions {
ellipsis?: string;
respectWordBoundaries?: boolean;
}
interface MaskOptions {
maskChar?: string;
visibleStart?: number;
visibleEnd?: number;
}
interface InterpolateOptions {
strict?: boolean;
fallback?: string;
transform?: (value: unknown, key: string) => string;
}
interface InitialsOptions {
limit?: number;
uppercase?: boolean;
}
interface QueryStringOptions {
arrayFormat?: 'repeat' | 'bracket' | 'comma';
skipNull?: boolean;
skipEmptyString?: boolean;
encode?: boolean;
sortKeys?: boolean;
}
Best Practices
All methods safely handle null and undefined inputs by converting them to empty strings:
StringUtils.capitalize(null); // Returns: ''
StringUtils.slugify(undefined); // Returns: ''
Chaining Operations
const processedString = StringUtils.compactWhitespace(
StringUtils.capitalize(' hello world ')
);
// Returns: 'Hello world'
Query String Building
For complex API requests:
const filters = {
categories: ['tech', 'design'],
dateRange: { start: '2024-01-01', end: '2024-12-31' },
active: true
};
const queryString = StringUtils.toQueryString(filters);
// Returns: 'active=true&categories=tech&categories=design&dateRange[end]=2024-12-31&dateRange[start]=2024-01-01'