A comprehensive JavaScript utility library for working with native objects that extends Array, Date, Function, Number, Object, RegExp, and String with powerful methods.
—
Comprehensive string manipulation methods providing case conversion, encoding, formatting, inflection, language detection, and advanced text processing capabilities for JavaScript strings.
import Sugar from "sugar";For CommonJS:
const Sugar = require("sugar");import Sugar from "sugar";
// String case conversion
const text = "hello world";
const camelCase = Sugar.String.camelize(text);
// "helloWorld"
// String manipulation
const padded = Sugar.String.pad("hello", 10, "*");
// "**hello***"
// String encoding
const encoded = Sugar.String.encodeBase64("Hello World");
// "SGVsbG8gV29ybGQ="
// Inflection
const word = "child";
const plural = Sugar.String.pluralize(word);
// "children"
// Language detection
const japanese = "こんにちは";
const hasHiragana = Sugar.String.hasHiragana(japanese);
// trueMethods for creating string ranges and sequences.
/**
* Creates string range from start to end character
* @param start - Starting character (default: 'a')
* @param end - Ending character
* @returns Array of characters in range
*/
function range(start?: string, end?: string): string[];Usage Examples:
// Create character ranges
const alphabet = Sugar.String.range('a', 'z');
// ['a', 'b', 'c', ..., 'z']
const numbers = Sugar.String.range('0', '9');
// ['0', '1', '2', ..., '9']Methods for accessing specific parts or characters of strings.
/**
* Get character at index with optional looping
* @param instance - Source string
* @param index - Character index (supports negative indexing)
* @param loop - Whether to loop around if index exceeds bounds
* @returns Character at index
*/
function at<T>(instance: string, index: number, loop?: boolean): string;
/**
* Get first n characters of string
* @param instance - Source string
* @param n - Number of characters to get (default: 1)
* @returns First n characters
*/
function first(instance: string, n?: number): string;
/**
* Get substring from index to end
* @param instance - Source string
* @param index - Starting index (default: 0)
* @returns Substring from index
*/
function from(instance: string, index?: number): string;
/**
* Get last n characters of string
* @param instance - Source string
* @param n - Number of characters to get (default: 1)
* @returns Last n characters
*/
function last(instance: string, n?: number): string;
/**
* Get substring from start to index
* @param instance - Source string
* @param index - Ending index
* @returns Substring to index
*/
function to(instance: string, index?: number): string;Usage Examples:
const text = "Hello World";
// Access with looping
const char = Sugar.String.at(text, -1);
// "d"
// Get first/last characters
const first3 = Sugar.String.first(text, 3);
// "Hel"
const last3 = Sugar.String.last(text, 3);
// "rld"
// Substring operations
const fromIndex = Sugar.String.from(text, 6);
// "World"
const toIndex = Sugar.String.to(text, 5);
// "Hello"Methods for converting between different case formats.
/**
* Convert string to camelCase
* @param instance - Source string
* @param upper - Whether to use UpperCamelCase (default: false)
* @returns Camelized string
*/
function camelize(instance: string, upper?: boolean): string;
/**
* Capitalize first letter of words
* @param instance - Source string
* @param lower - Whether to lowercase other letters (default: false)
* @param all - Whether to capitalize all words (default: false)
* @returns Capitalized string
*/
function capitalize(instance: string, lower?: boolean, all?: boolean): string;
/**
* Convert to dash-case format
* @param instance - Source string
* @returns Dasherized string
*/
function dasherize(instance: string): string;
/**
* Convert to URL-friendly parameter format
* @param instance - Source string
* @returns Parameterized string
*/
function parameterize(instance: string): string;
/**
* Add spaces before capital letters
* @param instance - Source string
* @returns Spacified string
*/
function spacify(instance: string): string;
/**
* Convert to Title Case
* @param instance - Source string
* @returns Titleized string
*/
function titleize(instance: string): string;
/**
* Convert to underscore_case format
* @param instance - Source string
* @returns Underscored string
*/
function underscore(instance: string): string;Usage Examples:
const text = "hello world example";
// Various case conversions
const camel = Sugar.String.camelize(text);
// "helloWorldExample"
const upperCamel = Sugar.String.camelize(text, true);
// "HelloWorldExample"
const capitalized = Sugar.String.capitalize(text, true, true);
// "Hello World Example"
const dashed = Sugar.String.dasherize("HelloWorld");
// "hello-world"
const param = Sugar.String.parameterize("Hello World! 123");
// "hello-world-123"
const spaced = Sugar.String.spacify("HelloWorld");
// "Hello World"
const title = Sugar.String.titleize(text);
// "Hello World Example"
const underscore = Sugar.String.underscore("HelloWorld");
// "hello_world"Methods for modifying, transforming, and manipulating string content.
/**
* Remove extra whitespace and compact string
* @param instance - Source string
* @returns Compacted string
*/
function compact(instance: string): string;
/**
* Insert string at specified index
* @param instance - Source string
* @param str - String to insert
* @param index - Index to insert at (default: length)
* @returns String with insertion
*/
function insert(instance: string, str: string, index?: number): string;
/**
* Pad string to specified length (both sides)
* @param instance - Source string
* @param num - Target length
* @param padding - Padding character (default: ' ')
* @returns Padded string
*/
function pad(instance: string, num: number, padding?: string): string;
/**
* Pad string to specified length (left side)
* @param instance - Source string
* @param num - Target length
* @param padding - Padding character (default: ' ')
* @returns Left-padded string
*/
function padLeft(instance: string, num: number, padding?: string): string;
/**
* Pad string to specified length (right side)
* @param instance - Source string
* @param num - Target length
* @param padding - Padding character (default: ' ')
* @returns Right-padded string
*/
function padRight(instance: string, num: number, padding?: string): string;
/**
* Remove first occurrence of pattern
* @param instance - Source string
* @param pattern - Pattern to remove (string or RegExp)
* @returns String with first match removed
*/
function remove(instance: string, pattern: any): string;
/**
* Remove all occurrences of pattern
* @param instance - Source string
* @param pattern - Pattern to remove (string or RegExp)
* @returns String with all matches removed
*/
function removeAll(instance: string, pattern: any): string;
/**
* Replace all occurrences of pattern
* @param instance - Source string
* @param pattern - Pattern to replace (string or RegExp)
* @param args - Replacement arguments
* @returns String with all matches replaced
*/
function replaceAll(instance: string, pattern: any, ...args: any[]): string;
/**
* Reverse string character order
* @param instance - Source string
* @returns Reversed string
*/
function reverse(instance: string): string;
/**
* Truncate string to specified length
* @param instance - Source string
* @param length - Maximum length
* @param from - Truncation direction ('left' | 'right' | 'middle')
* @param ellipsis - Ellipsis string (default: '...')
* @returns Truncated string
*/
function truncate(instance: string, length: number, from?: string, ellipsis?: string): string;
/**
* Truncate string at word boundary
* @param instance - Source string
* @param length - Maximum length
* @param from - Truncation direction ('left' | 'right' | 'middle')
* @param ellipsis - Ellipsis string (default: '...')
* @returns Truncated string at word boundary
*/
function truncateOnWord(instance: string, length: number, from?: string, ellipsis?: string): string;Usage Examples:
// String manipulation examples
const text = " hello world ";
const compacted = Sugar.String.compact(text);
// "hello world"
// Insertion
const inserted = Sugar.String.insert("Hello World", "Beautiful ", 6);
// "Hello Beautiful World"
// Padding
const padded = Sugar.String.pad("hello", 10, "*");
// "**hello***"
const leftPadded = Sugar.String.padLeft("42", 5, "0");
// "00042"
// Removal and replacement
const removed = Sugar.String.remove("hello world", "world");
// "hello "
const replaced = Sugar.String.replaceAll("hello world hello", "hello", "hi");
// "hi world hi"
// Reversal
const reversed = Sugar.String.reverse("hello");
// "olleh"
// Truncation
const truncated = Sugar.String.truncate("This is a very long string", 10);
// "This is..."
const wordTruncated = Sugar.String.truncateOnWord("This is a very long string", 10);
// "This is..."Methods for encoding and decoding strings in various formats.
/**
* Decode Base64 encoded string
* @param instance - Base64 encoded string
* @returns Decoded string
*/
function decodeBase64(instance: string): string;
/**
* Encode string to Base64
* @param instance - Source string
* @returns Base64 encoded string
*/
function encodeBase64(instance: string): string;
/**
* Escape HTML entities in string
* @param instance - Source string
* @returns HTML escaped string
*/
function escapeHTML(instance: string): string;
/**
* Unescape HTML entities in string
* @param instance - HTML escaped string
* @returns Unescaped string
*/
function unescapeHTML(instance: string): string;
/**
* URL encode string
* @param instance - Source string
* @param param - Whether encoding for parameter (default: false)
* @param partial - Whether partial encoding (default: false)
* @returns URL encoded string
*/
function escapeURL(instance: string, param?: boolean, partial?: boolean): string;
/**
* URL decode string
* @param instance - URL encoded string
* @param param - Whether decoding parameter (default: false)
* @param partial - Whether partial decoding (default: false)
* @returns URL decoded string
*/
function unescapeURL(instance: string, param?: boolean, partial?: boolean): string;Usage Examples:
// Base64 encoding
const original = "Hello World";
const encoded = Sugar.String.encodeBase64(original);
// "SGVsbG8gV29ybGQ="
const decoded = Sugar.String.decodeBase64(encoded);
// "Hello World"
// HTML encoding
const htmlText = "<h1>Hello & Goodbye</h1>";
const escaped = Sugar.String.escapeHTML(htmlText);
// "<h1>Hello & Goodbye</h1>"
const unescaped = Sugar.String.unescapeHTML(escaped);
// "<h1>Hello & Goodbye</h1>"
// URL encoding
const urlText = "hello world!";
const urlEncoded = Sugar.String.escapeURL(urlText);
// "hello%20world%21"
const urlDecoded = Sugar.String.unescapeURL(urlEncoded);
// "hello world!"Methods for working with HTML tags in strings.
/**
* Remove HTML tags from string
* @param instance - Source string with HTML
* @param tag - Specific tag to remove (default: all tags)
* @param replace - Replacement string (default: '')
* @returns String with tags removed
*/
function removeTags(instance: string, tag?: string, replace?: string): string;
/**
* Strip HTML tags from string (alias for removeTags)
* @param instance - Source string with HTML
* @param tag - Specific tag to remove (default: all tags)
* @param replace - Replacement string (default: '')
* @returns String with tags stripped
*/
function stripTags(instance: string, tag?: string, replace?: string): string;Usage Examples:
const htmlString = "<p>Hello <strong>World</strong>!</p>";
// Remove all tags
const noTags = Sugar.String.removeTags(htmlString);
// "Hello World!"
// Remove specific tags
const noStrong = Sugar.String.removeTags(htmlString, "strong");
// "<p>Hello World!</p>"
// Replace with custom text
const replaced = Sugar.String.removeTags(htmlString, "strong", "[BOLD]");
// "<p>Hello [BOLD]World[BOLD]!</p>"Methods for testing string properties and content.
/**
* Test if string is blank (contains only whitespace)
* @param instance - Source string
* @returns True if string is blank
*/
function isBlank(instance: string): boolean;
/**
* Test if string is empty (zero length)
* @param instance - Source string
* @returns True if string is empty
*/
function isEmpty(instance: string): boolean;Usage Examples:
// String testing
const empty = "";
const whitespace = " \n\t ";
const text = "hello";
Sugar.String.isEmpty(empty); // true
Sugar.String.isEmpty(whitespace); // false
Sugar.String.isEmpty(text); // false
Sugar.String.isBlank(empty); // true
Sugar.String.isBlank(whitespace); // true
Sugar.String.isBlank(text); // falseMethods for iterating over string components like characters, lines, and words.
/**
* Iterate over string characters
* @param instance - Source string
* @param eachCharFn - Function to call for each character
* @returns Array of characters or mapped values
*/
function chars<T>(instance: string, eachCharFn?: Function): T[];
/**
* Iterate over string character codes
* @param instance - Source string
* @param eachCodeFn - Function to call for each character code
* @returns Array of character codes or mapped values
*/
function codes<T>(instance: string, eachCodeFn?: Function): T[];
/**
* Iterate over pattern matches in string
* @param instance - Source string
* @param search - Search pattern (string or RegExp)
* @param eachFn - Function to call for each match
* @returns Array of matches or mapped values
*/
function forEach<T>(instance: string, search?: any, eachFn?: Function): T[];
/**
* Iterate over string lines
* @param instance - Source string
* @param eachLineFn - Function to call for each line
* @returns Array of lines or mapped values
*/
function lines<T>(instance: string, eachLineFn?: Function): T[];
/**
* Shift string characters by n positions
* @param instance - Source string
* @param n - Number of positions to shift
* @returns Shifted string
*/
function shift<T>(instance: string, n: number): string;
/**
* Iterate over string words
* @param instance - Source string
* @param eachWordFn - Function to call for each word
* @returns Array of words or mapped values
*/
function words<T>(instance: string, eachWordFn?: Function): T[];Usage Examples:
const text = "Hello World\nHow are you?";
// Character iteration
const characters = Sugar.String.chars(text);
// ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\n', ...]
// Character codes
const codes = Sugar.String.codes("ABC");
// [65, 66, 67]
// Line iteration
const lines = Sugar.String.lines(text);
// ["Hello World", "How are you?"]
// Word iteration
const words = Sugar.String.words(text);
// ["Hello", "World", "How", "are", "you"]
// Character shifting (Caesar cipher style)
const shifted = Sugar.String.shift("abc", 1);
// "bcd"Methods for converting strings to other types and formats.
/**
* Format string with arguments (sprintf-style)
* @param instance - Format string
* @param args - Arguments to substitute
* @returns Formatted string
*/
function format(instance: string, ...args: any[]): string;
/**
* Convert string to number
* @param instance - Source string
* @param base - Number base (default: 10)
* @returns Parsed number or NaN
*/
function toNumber(instance: string, base?: number): number;
/**
* Trim whitespace from left side of string
* @param instance - Source string
* @returns Left-trimmed string
*/
function trimLeft(instance: string): string;
/**
* Trim whitespace from right side of string
* @param instance - Source string
* @returns Right-trimmed string
*/
function trimRight(instance: string): string;Usage Examples:
// String formatting
const formatted = Sugar.String.format("Hello {0}, you are {1} years old", "Alice", 30);
// "Hello Alice, you are 30 years old"
// Number conversion
const number = Sugar.String.toNumber("42");
// 42
const hex = Sugar.String.toNumber("ff", 16);
// 255
// Trimming
const leftTrimmed = Sugar.String.trimLeft(" hello ");
// "hello "
const rightTrimmed = Sugar.String.trimRight(" hello ");
// " hello"Methods for grammatical inflection of words (pluralization, singularization, humanization).
/**
* Pluralize word based on number
* @param instance - Source word
* @param num - Number to determine plural form (default: 2)
* @returns Pluralized word
*/
function pluralize(instance: string, num?: number): string;
/**
* Singularize plural word
* @param instance - Plural word
* @returns Singularized word
*/
function singularize(instance: string): string;
/**
* Humanize string (make it readable)
* @param instance - Source string
* @returns Humanized string
*/
function humanize(instance: string): string;
/**
* Add custom acronym for inflection recognition
* @param src - Acronym string
*/
function addAcronym(src: string): void;
/**
* Add custom pluralization rule
* @param singular - Singular form
* @param plural - Plural form (optional, derived if not provided)
*/
function addPlural(singular: string, plural?: string): void;
/**
* Add custom humanization rule
* @param src - Source string
* @param human - Human-readable form
*/
function addHuman(src: string, human: string): void;Usage Examples:
// Basic inflection
const singular = "child";
const plural = Sugar.String.pluralize(singular);
// "children"
const backToSingular = Sugar.String.singularize("children");
// "child"
// Conditional pluralization
const item1 = Sugar.String.pluralize("apple", 1);
// "apple"
const items5 = Sugar.String.pluralize("apple", 5);
// "apples"
// Humanization
const humanized = Sugar.String.humanize("first_name");
// "First name"
// Custom rules
Sugar.String.addPlural("person", "people");
Sugar.String.addAcronym("API");
Sugar.String.addHuman("api_key", "API Key");Methods for detecting languages, scripts, and character sets in strings.
/**
* Test if string contains Arabic characters
* @param instance - Source string
* @returns True if contains Arabic characters
*/
function hasArabic(instance: string): boolean;
/**
* Test if string contains Cyrillic characters
* @param instance - Source string
* @returns True if contains Cyrillic characters
*/
function hasCyrillic(instance: string): boolean;
/**
* Test if string contains Devanagari characters
* @param instance - Source string
* @returns True if contains Devanagari characters
*/
function hasDevanagari(instance: string): boolean;
/**
* Test if string contains Greek characters
* @param instance - Source string
* @returns True if contains Greek characters
*/
function hasGreek(instance: string): boolean;
/**
* Test if string contains Hangul characters
* @param instance - Source string
* @returns True if contains Hangul characters
*/
function hasHangul(instance: string): boolean;
/**
* Test if string contains Han (Chinese) characters
* @param instance - Source string
* @returns True if contains Han characters
*/
function hasHan(instance: string): boolean;
/**
* Test if string contains Hebrew characters
* @param instance - Source string
* @returns True if contains Hebrew characters
*/
function hasHebrew(instance: string): boolean;
/**
* Test if string contains Hiragana characters
* @param instance - Source string
* @returns True if contains Hiragana characters
*/
function hasHiragana(instance: string): boolean;
/**
* Test if string contains Kana characters (Hiragana or Katakana)
* @param instance - Source string
* @returns True if contains Kana characters
*/
function hasKana(instance: string): boolean;
/**
* Test if string contains Katakana characters
* @param instance - Source string
* @returns True if contains Katakana characters
*/
function hasKatakana(instance: string): boolean;
/**
* Test if string contains Latin characters
* @param instance - Source string
* @returns True if contains Latin characters
*/
function hasLatin(instance: string): boolean;
/**
* Test if string contains Thai characters
* @param instance - Source string
* @returns True if contains Thai characters
*/
function hasThai(instance: string): boolean;
/**
* Test if string is purely Arabic
* @param instance - Source string
* @returns True if string is purely Arabic
*/
function isArabic(instance: string): boolean;
/**
* Test if string is purely Cyrillic
* @param instance - Source string
* @returns True if string is purely Cyrillic
*/
function isCyrillic(instance: string): boolean;
/**
* Test if string is purely Devanagari
* @param instance - Source string
* @returns True if string is purely Devanagari
*/
function isDevanagari(instance: string): boolean;
/**
* Test if string is purely Greek
* @param instance - Source string
* @returns True if string is purely Greek
*/
function isGreek(instance: string): boolean;
/**
* Test if string is purely Hangul
* @param instance - Source string
* @returns True if string is purely Hangul
*/
function isHangul(instance: string): boolean;
/**
* Test if string is purely Han (Chinese)
* @param instance - Source string
* @returns True if string is purely Han
*/
function isHan(instance: string): boolean;
/**
* Test if string is purely Hebrew
* @param instance - Source string
* @returns True if string is purely Hebrew
*/
function isHebrew(instance: string): boolean;
/**
* Test if string is purely Hiragana
* @param instance - Source string
* @returns True if string is purely Hiragana
*/
function isHiragana(instance: string): boolean;
/**
* Test if string is purely Kana (Hiragana or Katakana)
* @param instance - Source string
* @returns True if string is purely Kana
*/
function isKana(instance: string): boolean;
/**
* Test if string is purely Katakana
* @param instance - Source string
* @returns True if string is purely Katakana
*/
function isKatakana(instance: string): boolean;
/**
* Test if string is purely Latin
* @param instance - Source string
* @returns True if string is purely Latin
*/
function isLatin(instance: string): boolean;
/**
* Test if string is purely Thai
* @param instance - Source string
* @returns True if string is purely Thai
*/
function isThai(instance: string): boolean;Usage Examples:
// Script detection
const mixed = "Hello こんにちは مرحبا";
Sugar.String.hasLatin(mixed); // true
Sugar.String.hasHiragana(mixed); // true
Sugar.String.hasArabic(mixed); // true
// Pure script tests
const japanese = "こんにちは";
const english = "Hello";
Sugar.String.isHiragana(japanese); // true
Sugar.String.isLatin(english); // true
Sugar.String.isHiragana(english); // false
// Other scripts
const cyrillic = "Привет";
Sugar.String.hasCyrillic(cyrillic); // true
Sugar.String.isCyrillic(cyrillic); // true
const chinese = "你好";
Sugar.String.hasHan(chinese); // true
Sugar.String.isHan(chinese); // trueMethods for converting between full-width and half-width characters, and between Japanese writing systems.
/**
* Convert half-width to full-width characters
* @param instance - Source string
* @returns String with full-width characters
*/
function hankakuToZenkaku(instance: string): string;
/**
* Convert full-width to half-width characters
* @param instance - Source string
* @returns String with half-width characters
*/
function zenkakuToHankaku(instance: string): string;
/**
* Convert Hiragana to Katakana
* @param instance - Source string with Hiragana
* @returns String with Katakana characters
*/
function hiraganaToKatakana(instance: string): string;
/**
* Convert Katakana to Hiragana
* @param instance - Source string with Katakana
* @returns String with Hiragana characters
*/
function katakanaToHiragana(instance: string): string;Usage Examples:
// Character width conversion
const halfWidth = "ABC123";
const fullWidth = Sugar.String.hankakuToZenkaku(halfWidth);
// "ABC123"
const backToHalf = Sugar.String.zenkakuToHankaku(fullWidth);
// "ABC123"
// Japanese character conversion
const hiragana = "こんにちは";
const katakana = Sugar.String.hiraganaToKatakana(hiragana);
// "コンニチハ"
const backToHiragana = Sugar.String.katakanaToHiragana(katakana);
// "こんにちは"/**
* Function type for mapping operations
*/
type mapFn<T, U> = (item: T, index?: number) => U;
/**
* Configuration options for extending native objects
*/
interface ExtendOptions {
methods?: Array<string>;
except?: Array<string>;
namespaces?: Array<any>;
enhance?: boolean;
enhanceString?: boolean;
enhanceArray?: boolean;
objectPrototype?: boolean;
}
/**
* Chainable interface for Sugar operations
*/
interface SugarDefaultChainable<RawValue> {
raw: RawValue;
valueOf(): RawValue extends string | number | boolean ? RawValue : any;
toString(): string;
}