Comprehensive String polyfills including static methods for string creation, instance methods for manipulation, search, formatting, and Unicode handling.
Static methods for creating strings from various sources and working with Unicode code points.
/**
* String constructor with enhanced static methods
*/
interface StringConstructor {
/**
* Create string from Unicode code points
* @param codePoints - Unicode code point values
*/
fromCodePoint(...codePoints: number[]): string;
/**
* Create raw string from template literal
* @param template - Template object with raw strings
* @param substitutions - Values to substitute
*/
raw(template: { raw: readonly string[] | ArrayLike<string> }, ...substitutions: any[]): string;
}Usage Examples:
import String from 'core-js-pure/stable/string';
// String.fromCodePoint - Create from Unicode code points
const emoji = String.fromCodePoint(0x1F600, 0x1F601); // "ππ"
const text = String.fromCodePoint(72, 101, 108, 108, 111); // "Hello"
// String.raw - Raw template strings
const path = String.raw`C:\Users\Name\Documents`; // "C:\Users\Name\Documents"
const regex = String.raw`\d+\.\d+`; // "\\d+\\.\\d+"Methods for searching within strings and testing string patterns.
interface String {
/**
* Check if string contains substring
* @param searchString - String to search for
* @param position - Position to start search from
*/
includes(searchString: string, position?: number): boolean;
/**
* Check if string starts with substring
* @param searchString - String to check for
* @param position - Position to start check from
*/
startsWith(searchString: string, position?: number): boolean;
/**
* Check if string ends with substring
* @param searchString - String to check for
* @param length - Length of string to consider
*/
endsWith(searchString: string, length?: number): boolean;
/**
* Find first occurrence of substring
* @param searchValue - Value to search for
* @param fromIndex - Index to start search from
*/
indexOf(searchValue: string, fromIndex?: number): number;
/**
* Find last occurrence of substring
* @param searchValue - Value to search for
* @param fromIndex - Index to start search from
*/
lastIndexOf(searchValue: string, fromIndex?: number): number;
/**
* Search for pattern using regular expression
* @param regexp - Regular expression to match
*/
search(regexp: string | RegExp): number;
/**
* Match string against regular expression
* @param regexp - Regular expression to match
*/
match(regexp: string | RegExp): RegExpMatchArray | null;
/**
* Get all matches of regular expression
* @param regexp - Global regular expression
*/
matchAll(regexp: RegExp): IterableIterator<RegExpMatchArray>;
}Usage Examples:
import { includes, startsWith, endsWith } from 'core-js-pure/stable/string';
// Search methods
const text = "The quick brown fox jumps over the lazy dog";
console.log(text.includes("quick")); // true
console.log(text.includes("Quick")); // false
console.log(text.includes("fox", 20)); // false (search after position 20)
console.log(text.startsWith("The")); // true
console.log(text.startsWith("quick", 4)); // true (from position 4)
console.log(text.endsWith("dog")); // true
console.log(text.endsWith("lazy", 40)); // true (considering first 40 chars)
// Pattern matching
const email = "user@example.com";
const emailPattern = /(\w+)@(\w+\.\w+)/g;
const matches = [...email.matchAll(emailPattern)];
console.log(matches[0]); // ["user@example.com", "user", "example.com", ...]Methods for transforming and formatting strings.
interface String {
/**
* Repeat string specified number of times
* @param count - Number of repetitions
*/
repeat(count: number): string;
/**
* Pad string at start to target length
* @param targetLength - Desired final length
* @param padString - String to pad with
*/
padStart(targetLength: number, padString?: string): string;
/**
* Pad string at end to target length
* @param targetLength - Desired final length
* @param padString - String to pad with
*/
padEnd(targetLength: number, padString?: string): string;
/**
* Remove whitespace from both ends
*/
trim(): string;
/**
* Remove whitespace from start
*/
trimStart(): string;
trimLeft(): string; // Alias for trimStart
/**
* Remove whitespace from end
*/
trimEnd(): string;
trimRight(): string; // Alias for trimEnd
/**
* Replace first occurrence of pattern
* @param searchValue - Pattern to search for
* @param replaceValue - Replacement string or function
*/
replace(searchValue: string | RegExp, replaceValue: string | ((substring: string, ...args: any[]) => string)): string;
/**
* Replace all occurrences of pattern
* @param searchValue - Pattern to search for
* @param replaceValue - Replacement string or function
*/
replaceAll(searchValue: string | RegExp, replaceValue: string | ((substring: string, ...args: any[]) => string)): string;
/**
* Convert to uppercase
*/
toUpperCase(): string;
/**
* Convert to lowercase
*/
toLowerCase(): string;
}Usage Examples:
import { repeat, padStart, padEnd, trim, replaceAll } from 'core-js-pure/stable/string';
// String repetition and padding
console.log("Ha".repeat(3)); // "HaHaHa"
console.log("5".padStart(3, "0")); // "005"
console.log("Price: ".padEnd(10, ".")); // "Price: ..."
// Whitespace trimming
const messy = " Hello World ";
console.log(messy.trim()); // "Hello World"
console.log(messy.trimStart()); // "Hello World "
console.log(messy.trimEnd()); // " Hello World"
// String replacement
const text = "The cat in the hat";
console.log(text.replace("cat", "dog")); // "The dog in the hat"
console.log(text.replaceAll("at", "ot")); // "The cot in the hot"
// Format numbers with padding
const formatNumber = (num, width) =>
num.toString().padStart(width, '0');
console.log(formatNumber(42, 5)); // "00042"
console.log(formatNumber(123, 3)); // "123"
// Clean and normalize text
const cleanText = (str) =>
str.trim()
.replaceAll(/\s+/g, ' ')
.toLowerCase();
console.log(cleanText(" Hello World ")); // "hello world"Methods for accessing string characters and working with Unicode.
interface String {
/**
* Get character at index (supports negative indices)
* @param index - Index to access
*/
at(index: number): string | undefined;
/**
* Get Unicode code point at position
* @param pos - Position in string
*/
codePointAt(pos: number): number | undefined;
/**
* Check if string is well-formed Unicode
*/
isWellFormed(): boolean;
/**
* Convert to well-formed Unicode string
*/
toWellFormed(): string;
/**
* Split string into array
* @param separator - Separator pattern
* @param limit - Maximum number of splits
*/
split(separator?: string | RegExp, limit?: number): string[];
/**
* Get string iterator
*/
[Symbol.iterator](): IterableIterator<string>;
}Usage Examples:
import { at, codePointAt, isWellFormed, toWellFormed } from 'core-js-pure/stable/string';
// Modern string access
const text = "HelloπWorld";
console.log(text.at(0)); // "H"
console.log(text.at(-1)); // "d"
console.log(text.at(5)); // "π"
// Unicode handling
console.log(text.codePointAt(5)); // 128075 (wave emoji code point)
console.log(String.fromCodePoint(128075)); // "π"
// Well-formed Unicode checking
const wellFormed = "Hello World";
const malformed = "Hello\uD800World"; // Lone surrogate
console.log(wellFormed.isWellFormed()); // true
console.log(malformed.isWellFormed()); // false
console.log(malformed.toWellFormed()); // "Hello\uFFFDWorld" (replacement char)
// String iteration respects Unicode
const emojis = "π¨βπ©βπ§βπ¦π";
for (const char of emojis) {
console.log(char); // Correctly iterates over complex emoji sequences
}
// Advanced splitting
const csv = "name,age,city";
const data = "Alice,25,NYC;Bob,30,LA;Charlie,35,Chicago";
const headers = csv.split(',');
const rows = data.split(';').map(row => row.split(','));
console.log(headers); // ["name", "age", "city"]
console.log(rows); // [["Alice", "25", "NYC"], ["Bob", "30", "LA"], ...]Helper methods for common string formatting tasks.
/**
* Virtual string methods - pure functions that don't modify prototypes
* Available via: core-js-pure/string/virtual/{method-name}
*/
// Example virtual method signatures
declare function repeat(str: string, count: number): string;
declare function padStart(str: string, targetLength: number, padString?: string): string;
declare function padEnd(str: string, targetLength: number, padString?: string): string;
declare function includes(str: string, searchString: string, position?: number): boolean;Usage Examples:
import repeat from 'core-js-pure/string/virtual/repeat';
import padStart from 'core-js-pure/string/virtual/pad-start';
import padEnd from 'core-js-pure/string/virtual/pad-end';
// Use as pure functions
const border = repeat('-', 20); // "--------------------"
const formatted = padStart("42", 5, "0"); // "00042"
const label = padEnd("Name:", 10, " "); // "Name: "
// Create formatting utilities
const createFormatter = (width, align = 'left', fill = ' ') => {
return (str) => {
const text = String(str);
if (align === 'right') return padStart(text, width, fill);
if (align === 'center') {
const totalPad = width - text.length;
const leftPad = Math.floor(totalPad / 2);
return padEnd(padStart(text, text.length + leftPad, fill), width, fill);
}
return padEnd(text, width, fill);
};
};
const rightAlign = createFormatter(10, 'right');
const centerAlign = createFormatter(10, 'center');
console.log(rightAlign("42")); // " 42"
console.log(centerAlign("Hello")); // " Hello "import { trim, replaceAll, split, includes } from 'core-js-pure/stable/string';
// Clean and process text data
const processText = (text) => {
return text
.trim()
.replaceAll(/\s+/g, ' ') // Normalize whitespace
.replaceAll(/[^\w\s]/g, '') // Remove special characters
.toLowerCase()
.split(' ')
.filter(word => word.length > 2); // Filter short words
};
const input = " Hello, World! How are you today? ";
const words = processText(input);
console.log(words); // ["hello", "world", "how", "are", "you", "today"]import { includes, replaceAll } from 'core-js-pure/stable/string';
// Simple template replacement system
const renderTemplate = (template, data) => {
let result = template;
for (const [key, value] of Object.entries(data)) {
const placeholder = `{{${key}}}`;
if (includes(result, placeholder)) {
result = replaceAll(result, placeholder, String(value));
}
}
return result;
};
const template = "Hello {{name}}, you have {{count}} messages.";
const data = { name: "Alice", count: 5 };
const message = renderTemplate(template, data);
// "Hello Alice, you have 5 messages."import { trim, startsWith, endsWith, includes, replaceAll } from 'core-js-pure/stable/string';
// Comprehensive input validation
const validators = {
email: (str) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str),
phone: (str) => /^\+?[\d\s\-()]{10,}$/.test(str),
url: (str) => startsWith(str, 'http://') || startsWith(str, 'https://'),
notEmpty: (str) => trim(str).length > 0,
noScript: (str) => !includes(str.toLowerCase(), '<script')
};
const sanitizers = {
removeExtraSpaces: (str) => replaceAll(str, /\s+/g, ' '),
removeSpecialChars: (str) => replaceAll(str, /[<>'"&]/g, ''),
normalizePhone: (str) => replaceAll(str, /[\s\-()]/g, '')
};
const validateAndSanitize = (input, rules) => {
let processed = trim(input);
// Apply sanitizers
for (const sanitizer of rules.sanitizers || []) {
processed = sanitizers[sanitizer](processed);
}
// Apply validators
for (const validator of rules.validators || []) {
if (!validators[validator](processed)) {
throw new Error(`Validation failed: ${validator}`);
}
}
return processed;
};
// Usage
const userInput = " alice@example.com ";
const cleanEmail = validateAndSanitize(userInput, {
sanitizers: ['removeExtraSpaces'],
validators: ['notEmpty', 'email', 'noScript']
});