- Spec files
npm-lodash
Describes: pkg:npm/lodash@4.5.x
- Description
- Comprehensive JavaScript utility library with 300+ methods for arrays, objects, strings, functions, and more.
- Author
- tessl
- Last updated
string-methods.md docs/
1# String Methods23String manipulation utilities for case conversion, formatting, templating, and parsing. These methods provide comprehensive text processing capabilities for JavaScript applications.45## Capabilities67### Case Conversion89#### camelCase & Related Cases10Converts strings to various naming conventions.1112```javascript { .api }13/**14* Converts string to camel case15* @param string - The string to convert16* @returns Returns the camel cased string17*/18function camelCase(string);1920/**21* Converts string to kebab case22* @param string - The string to convert23* @returns Returns the kebab cased string24*/25function kebabCase(string);2627/**28* Converts string to snake case29* @param string - The string to convert30* @returns Returns the snake cased string31*/32function snakeCase(string);3334/**35* Converts string to start case36* @param string - The string to convert37* @returns Returns the start cased string38*/39function startCase(string);4041/**42* Converts string to lower case43* @param string - The string to convert44* @returns Returns the lower case string45*/46function lowerCase(string);4748/**49* Converts string to upper case50* @param string - The string to convert51* @returns Returns the upper case string52*/53function upperCase(string);54```5556#### Capitalization57Capitalizes or changes case of first characters.5859```javascript { .api }60/**61* Converts the first character of string to upper case and the remaining to lower case62* @param string - The string to capitalize63* @returns Returns the capitalized string64*/65function capitalize(string);6667/**68* Converts the first character of string to lower case69* @param string - The string to convert70* @returns Returns the converted string71*/72function lowerFirst(string);7374/**75* Converts the first character of string to upper case76* @param string - The string to convert77* @returns Returns the converted string78*/79function upperFirst(string);80```8182#### Native Case Methods83Direct access to native string case methods.8485```javascript { .api }86/**87* Converts string, as a whole, to lower case just like String#toLowerCase88* @param value - The string to convert89* @returns Returns the lower cased string90*/91function toLower(value);9293/**94* Converts string, as a whole, to upper case just like String#toUpperCase95* @param value - The string to convert96* @returns Returns the upper cased string97*/98function toUpper(value);99```100101### String Padding & Trimming102103#### Padding104Pads strings to a specified length.105106```javascript { .api }107/**108* Pads string on the left and right sides if it's shorter than length109* @param string - The string to pad110* @param length - The padding length111* @param chars - The string used as padding112* @returns Returns the padded string113*/114function pad(string, length = 0, chars = ' ');115116/**117* Pads string on the right side if it's shorter than length118* @param string - The string to pad119* @param length - The padding length120* @param chars - The string used as padding121* @returns Returns the padded string122*/123function padEnd(string, length = 0, chars = ' ');124125/**126* Pads string on the left side if it's shorter than length127* @param string - The string to pad128* @param length - The padding length129* @param chars - The string used as padding130* @returns Returns the padded string131*/132function padStart(string, length = 0, chars = ' ');133```134135#### Trimming136Removes whitespace or specified characters from strings.137138```javascript { .api }139/**140* Removes leading and trailing whitespace or specified characters from string141* @param string - The string to trim142* @param chars - The characters to trim143* @returns Returns the trimmed string144*/145function trim(string, chars = whitespace);146147/**148* Removes trailing whitespace or specified characters from string149* @param string - The string to trim150* @param chars - The characters to trim151* @returns Returns the trimmed string152*/153function trimEnd(string, chars = whitespace);154155/**156* Removes leading whitespace or specified characters from string157* @param string - The string to trim158* @param chars - The characters to trim159* @returns Returns the trimmed string160*/161function trimStart(string, chars = whitespace);162```163164### String Testing165166#### startsWith & endsWith167Tests string prefixes and suffixes.168169```javascript { .api }170/**171* Checks if string starts with target string172* @param string - The string to inspect173* @param target - The string to search for174* @param position - The position to search from175* @returns Returns true if string starts with target, else false176*/177function startsWith(string, target, position = 0);178179/**180* Checks if string ends with target string181* @param string - The string to inspect182* @param target - The string to search for183* @param position - The position to search up to184* @returns Returns true if string ends with target, else false185*/186function endsWith(string, target, position = string.length);187```188189### String Manipulation190191#### repeat192Repeats the given string n times.193194```javascript { .api }195/**196* Repeats the given string n times197* @param string - The string to repeat198* @param n - The number of times to repeat the string199* @returns Returns the repeated string200*/201function repeat(string, n = 1);202```203204#### replace205Replaces matches for pattern in string with replacement.206207```javascript { .api }208/**209* Replaces matches for pattern in string with replacement210* @param string - The string to modify211* @param pattern - The pattern to replace212* @param replacement - The match replacement213* @returns Returns the modified string214*/215function replace(string, pattern, replacement);216```217218#### split219Splits string by separator until limit is reached.220221```javascript { .api }222/**223* Splits string by separator until limit is reached224* @param string - The string to split225* @param separator - The separator pattern to split by226* @param limit - The length to truncate results to227* @returns Returns the string segments228*/229function split(string, separator, limit);230```231232#### truncate233Truncates string if it's longer than the given maximum string length.234235```javascript { .api }236/**237* Truncates string if it's longer than the given maximum string length238* @param string - The string to truncate239* @param options - The options object240* @returns Returns the truncated string241*/242function truncate(string, options);243244// Options interface245interface TruncateOptions {246length?: number; // Maximum string length (default: 30)247omission?: string; // String to indicate text is omitted (default: '...')248separator?: RegExp | string; // Separator pattern to truncate to249}250```251252### String Processing253254#### deburr255Deburrs string by converting Latin-1 Supplement and Latin Extended-A letters to basic Latin letters.256257```javascript { .api }258/**259* Deburrs string by converting Latin-1 Supplement and Latin Extended-A letters to basic Latin letters and removing combining diacritical marks260* @param string - The string to deburr261* @returns Returns the deburred string262*/263function deburr(string);264```265266#### words267Splits string into an array of its words.268269```javascript { .api }270/**271* Splits string into an array of its words272* @param string - The string to inspect273* @param pattern - The pattern to match words274* @returns Returns the words of string275*/276function words(string, pattern);277```278279### HTML & RegExp Escaping280281#### escape & unescape282Converts characters to HTML entities and vice versa.283284```javascript { .api }285/**286* Converts the characters "&", "<", ">", '"', and "'" in string to their corresponding HTML entities287* @param string - The string to escape288* @returns Returns the escaped string289*/290function escape(string);291292/**293* The inverse of escape; converts HTML entities "&", "<", ">", """, and "'" to their corresponding characters294* @param string - The string to unescape295* @returns Returns the unescaped string296*/297function unescape(string);298```299300#### escapeRegExp301Escapes RegExp special characters.302303```javascript { .api }304/**305* Escapes the RegExp special characters "^", "$", "\", ".", "*", "+", "?", "(", ")", "[", "]", "{", "}", and "|" in string306* @param string - The string to escape307* @returns Returns the escaped string308*/309function escapeRegExp(string);310```311312### Number Parsing313314#### parseInt315Converts string to an integer of the specified radix.316317```javascript { .api }318/**319* Converts string to an integer of the specified radix320* @param string - The string to convert321* @param radix - The radix to interpret the value by322* @returns Returns the converted integer323*/324function parseInt(string, radix = 10);325```326327### Template Processing328329#### template330Creates a compiled template function that can interpolate data properties.331332```javascript { .api }333/**334* Creates a compiled template function that can interpolate data properties in "interpolate" delimiters, HTML-escape interpolated data properties in "escape" delimiters, and execute JavaScript in "evaluate" delimiters335* @param string - The template string336* @param options - The options object337* @returns Returns the compiled template function338*/339function template(string, options);340341// Template options interface342interface TemplateOptions {343escape?: RegExp; // HTML "escape" delimiter344evaluate?: RegExp; // JavaScript "evaluate" delimiter345interpolate?: RegExp; // Data property "interpolate" delimiter346sourceURL?: string; // Source URL of the template347variable?: string; // Data object variable name348imports?: object; // Object of template imports349}350351// Compiled template function352interface CompiledTemplate {353(data?: object): string;354source: string;355}356```357358## Template Syntax359360Lodash templates support three types of delimiters:361362```javascript { .api }363// Interpolation: <%= variable %>364const template1 = template('Hello <%= name %>!');365template1({ name: 'John' }); // → 'Hello John!'366367// HTML Escaping: <%- variable %>368const template2 = template('User: <%- user %>');369template2({ user: '<script>' }); // → 'User: <script>'370371// JavaScript Evaluation: <% code %>372const template3 = template('<% if (user) { %>Hello <%= user %>!<% } %>');373template3({ user: 'John' }); // → 'Hello John!'374```375376## Usage Examples377378```javascript379import {380camelCase, kebabCase, snakeCase, capitalize,381pad, trim, startsWith, endsWith, repeat,382replace, split, truncate, escape, template383} from "lodash";384385// Case conversion386const title = 'hello world';387console.log(camelCase(title)); // 'helloWorld'388console.log(kebabCase(title)); // 'hello-world'389console.log(snakeCase(title)); // 'hello_world'390console.log(capitalize(title)); // 'Hello world'391392// String formatting393const text = ' hello world ';394console.log(trim(text)); // 'hello world'395console.log(pad('42', 5, '0')); // '00420'396397// String testing398const filename = 'document.pdf';399console.log(startsWith(filename, 'doc')); // true400console.log(endsWith(filename, '.pdf')); // true401402// String manipulation403console.log(repeat('*', 5)); // '*****'404console.log(replace('hello world', 'world', 'universe')); // 'hello universe'405406// Text processing407const sentence = 'The quick brown fox jumps over the lazy dog';408console.log(split(sentence, ' ', 3)); // ['The', 'quick', 'brown']409console.log(truncate(sentence, { length: 20 })); // 'The quick brown fox...'410411// HTML safety412const userInput = '<script>alert("xss")</script>';413console.log(escape(userInput)); // '<script>alert("xss")</script>'414415// Template processing416const greetingTemplate = template('Hello <%= name %>! You have <%= count %> messages.');417const greeting = greetingTemplate({ name: 'Alice', count: 3 });418console.log(greeting); // 'Hello Alice! You have 3 messages.'419420// Advanced templates421const listTemplate = template(`422<ul>423<% items.forEach(function(item) { %>424<li><%- item.name %> - $<%= item.price %></li>425<% }); %>426</ul>427`);428429const items = [430{ name: 'Coffee & Cake', price: 4.99 },431{ name: 'Tea', price: 2.99 }432];433434const html = listTemplate({ items });435// Generates properly escaped HTML list436437// Complex case conversions438const apiEndpoint = 'GET_USER_PROFILE';439console.log(camelCase(apiEndpoint)); // 'getUserProfile'440console.log(kebabCase(apiEndpoint)); // 'get-user-profile'441442// String cleaning and normalization443const messyString = ' Café & Restaurant ';444const cleaned = trim(deburr(messyString)); // 'Cafe & Restaurant'445446// Pattern-based word splitting447const text2 = 'camelCaseString';448console.log(words(text2)); // ['camel', 'Case', 'String']449450// Safe string building451const buildUrl = (base, ...segments) => {452const cleanBase = trimEnd(base, '/');453const cleanSegments = segments.map(s => trim(s, '/'));454return [cleanBase, ...cleanSegments].join('/');455};456457console.log(buildUrl('https://api.example.com/', '/users/', '/123/'));458// 'https://api.example.com/users/123'459```