or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

array-operations.mdfunction-utilities.mdindex.mdmath-operations.mdobject-operations.mdpromise-utilities.mdstring-operations.mdtime-performance.mdtype-guards.md
tile.json

string-operations.mddocs/

String Operations

String manipulation utilities providing templating, formatting, transformation, and text processing functions for common string operations.

Capabilities

String Formatting & Transformation

Basic string formatting and transformation utilities.

/**
 * Replace backslashes with forward slashes
 * @param str - String to process
 * @returns String with backslashes converted to forward slashes
 */
function slash(str: string): string;

/**
 * Ensure prefix of a string
 * @param prefix - Prefix to ensure
 * @param str - String to modify
 * @returns String guaranteed to start with the prefix
 */
function ensurePrefix(prefix: string, str: string): string;

/**
 * Ensure suffix of a string
 * @param suffix - Suffix to ensure
 * @param str - String to modify
 * @returns String guaranteed to end with the suffix
 */
function ensureSuffix(suffix: string, str: string): string;

/**
 * First letter uppercase, other lowercase
 * @param str - String to capitalize
 * @returns Capitalized string
 */
function capitalize(str: string): string;

Usage Examples:

import { slash, ensurePrefix, ensureSuffix, capitalize } from "@antfu/utils";

// Path normalization
const windowsPath = "C:\\Users\\Documents\\file.txt";
const normalizedPath = slash(windowsPath);
// "C:/Users/Documents/file.txt"

// URL building
let url = "example.com";
url = ensurePrefix("https://", url); // "https://example.com"
url = ensureSuffix("/", url); // "https://example.com/"

// Text formatting
const name = capitalize("jOHN DOE"); // "John doe"
const title = capitalize("hello world"); // "Hello world"

Template Processing

Powerful template string processing with both indexed and named variable substitution.

/**
 * Dead simple template engine, just like Python's `.format()`
 * Support passing variables as either in index based or object/name based approach
 * While using object/name based approach, you can pass a fallback value as the third argument
 */
function template(str: string, object: Record<string | number, any>, fallback?: string | ((key: string) => string)): string;
function template(str: string, ...args: (string | number | bigint | undefined | null)[]): string;

Usage Examples:

import { template } from "@antfu/utils";

// Index-based templating
const indexedResult = template(
  'Hello {0}! My name is {1}.',
  'Inès',
  'Anthony'
);
// "Hello Inès! My name is Anthony."

// Object-based templating
const namedResult = template(
  '{greet}! My name is {name}.',
  { greet: 'Hello', name: 'Anthony' }
);
// "Hello! My name is Anthony."

// With fallback values
const withFallback = template(
  '{greet}! My name is {name}.',
  { greet: 'Hello' }, // name is missing
  'placeholder'
);
// "Hello! My name is placeholder."

// Dynamic fallback function
const dynamicFallback = template(
  'User: {username}, Role: {role}',
  { username: 'alice' },
  (key) => key.toUpperCase()
);
// "User: alice, Role: ROLE"

// Email templates
const emailTemplate = template(
  'Dear {customerName}, your order #{orderId} has been {status}.',
  {
    customerName: 'John Smith',
    orderId: '12345',
    status: 'shipped'
  }
);

// Dynamic URL generation
const apiUrl = template(
  'https://api.{domain}/v{version}/users/{userId}',
  {
    domain: 'example.com',
    version: '2',
    userId: '123'
  }
);

Text Generation

Utilities for generating random strings and text processing.

/**
 * Generate a random string
 * @param size - Length of the random string (default: 16)
 * @param dict - Character dictionary to use (default: URL-safe alphabet)
 * @returns Random string of specified length
 */
function randomStr(size?: number, dict?: string): string;

Usage Examples:

import { randomStr } from "@antfu/utils";

// Generate random IDs
const defaultId = randomStr(); // 16 characters, URL-safe
const shortId = randomStr(8); // 8 characters
const longId = randomStr(32); // 32 characters

// Custom character sets
const numericId = randomStr(10, '0123456789');
const alphaId = randomStr(12, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
const customId = randomStr(8, 'ABC123');

// Common use cases
function generateSessionId(): string {
  return randomStr(24); // 24-character session ID
}

function generateToken(): string {
  return randomStr(32, 'ABCDEFGHIJKMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789');
}

// Generate temporary filenames
function createTempFile(extension: string = '.tmp'): string {
  return `temp_${randomStr(8)}${extension}`;
}

Text Processing

Advanced text processing and formatting utilities.

/**
 * Remove common leading whitespace from a template string.
 * Will also remove empty lines at the beginning and end.
 * @param str - Template string or regular string to unindent
 * @returns String with common indentation removed
 */
function unindent(str: TemplateStringsArray | string): string;

Usage Examples:

import { unindent } from "@antfu/utils";

// Template literal processing
const code = unindent`
  if (condition) {
    doSomething();
    doSomethingElse();
  }
`;
// Result: "if (condition) {\n  doSomething();\n  doSomethingElse();\n}"

// String processing
const indentedText = `
    Line 1
    Line 2
      Indented line
    Line 3
`;
const cleanText = unindent(indentedText);
// Result: "Line 1\nLine 2\n  Indented line\nLine 3"

// Code generation
function generateFunction(name: string, body: string): string {
  return unindent`
    function ${name}() {
      ${body}
    }
  `;
}

// SQL query formatting
const query = unindent`
  SELECT users.name, profiles.bio
  FROM users
  JOIN profiles ON users.id = profiles.user_id
  WHERE users.active = true
  ORDER BY users.created_at DESC
`;

// HTML template processing
const htmlTemplate = unindent`
  <div class="container">
    <h1>Welcome</h1>
    <p>This is a paragraph</p>
  </div>
`;

// Configuration file generation
function generateConfig(options: Record<string, any>): string {
  const configLines = Object.entries(options)
    .map(([key, value]) => `${key} = ${JSON.stringify(value)}`)
    .join('\n  ');
    
  return unindent`
    [settings]
    ${configLines}
  `;
}