Skip to main content

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
options
SlugifyOptions
Optional configuration object
separator
string
default:"-"
Character to use as separator
lowercase
boolean
default:"true"
Convert to lowercase
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
string
default:"es-AR"
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
string
default:"es-AR"
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
maxLength
number
required
Maximum length including ellipsis
options
TruncateOptions
Optional configuration object
ellipsis
string
default:"…"
String to append when truncated
respectWordBoundaries
boolean
default:"true"
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
options
MaskOptions
Optional configuration object
maskChar
string
default:"•"
Character to use for masking
visibleStart
number
default:"0"
Number of characters visible at start
visibleEnd
number
default:"4"
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
required
Template string with syntax
params
Record<string, unknown>
required
Object containing values for placeholders
options
InterpolateOptions
Optional configuration object
strict
boolean
default:"false"
Throw error for missing values
fallback
string
default:"''"
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
options
InitialsOptions
Optional configuration object
limit
number
default:"2"
Maximum number of initials to extract
uppercase
boolean
default:"true"
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
options
QueryStringOptions
Optional configuration object
arrayFormat
'repeat' | 'bracket' | 'comma'
default:"repeat"
Format for array serialization
skipNull
boolean
default:"true"
Skip null values
skipEmptyString
boolean
default:"false"
Skip empty string values
encode
boolean
default:"true"
URL encode keys and values
sortKeys
boolean
default:"true"
Sort keys alphabetically
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

Input Validation

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'