Lodash - String
Lodash - String Methods
Section titled “Lodash - String Methods”Lodash provides a variety of utility functions for common string manipulations, complementing JavaScript’s built-in String methods. These functions often offer convenient solutions for tasks like changing case, trimming, padding, escaping HTML, and creating templates.
While native methods like toLowerCase(), toUpperCase(), trim(), padStart(), padEnd(), startsWith(), endsWith(), includes(), replace(), and template literals handle many basic needs, Lodash offers useful additions.
Key String Manipulation Methods
Section titled “Key String Manipulation Methods”| Method & Syntax | Description |
|---|---|
| camelCase _.camelCase([string=”]) | Converts string to camel case (e.g., ‘foo bar’ -> ‘fooBar’). |
| kebabCase _.kebabCase([string=”]) | Converts string to kebab case (e.g., ‘Foo Bar’ -> ‘foo-bar’). |
| snakeCase _.snakeCase([string=”]) | Converts string to snake case (e.g., ‘Foo Bar’ -> ‘foo_bar’). |
| startCase _.startCase([string=”]) | Converts string to start case (e.g., ‘—foo-bar—’ -> ‘Foo Bar’). Capitalizes the first letter of each word. |
| capitalize _.capitalize([string=”]) | Converts the first character of string to upper case and the remaining to lower case. |
| lowerCase _.lowerCase([string=”]) | Converts string, as space separated words, to lower case. |
| lowerFirst _.lowerFirst([string=”]) | Converts the first character of string to lower case. |
| upperCase _.upperCase([string=”]) | Converts string, as space separated words, to upper case. |
| upperFirst _.upperFirst([string=”]) | Converts the first character of string to upper case. |
| pad _.pad([string=”], [length=0], [chars=’ ’]) | Pads string on the left and right sides if it’s shorter than length. Padding characters are truncated if they can’t be evenly divided. |
| padEnd _.padEnd([string=”], [length=0], [chars=’ ’]) | Pads string on the right side if it’s shorter than length. Native equivalent: String.prototype.padEnd(). |
| padStart _.padStart([string=”], [length=0], [chars=’ ’]) | Pads string on the left side if it’s shorter than length. Native equivalent: String.prototype.padStart(). |
| trim _.trim([string=”], [chars=whitespace]) | Removes leading and trailing whitespace or specified characters from string. Native equivalent: String.prototype.trim() (for whitespace). |
| trimEnd _.trimEnd([string=”], [chars=whitespace]) | Removes trailing whitespace or specified characters. Native equivalent: String.prototype.trimEnd() / trimRight(). |
| trimStart _.trimStart([string=”], [chars=whitespace]) | Removes leading whitespace or specified characters. Native equivalent: String.prototype.trimStart() / trimLeft(). |
| repeat _.repeat([string=”], [n=1]) | Repeats the given string n times. Native equivalent: String.prototype.repeat(). |
| split _.split([string=”], separator, [limit]) | Splits string by separator. Native equivalent: String.prototype.split(). |
| escape _.escape([string=”]) | Converts the characters ’&’, ’<’, ’>’, ’”’, and ”’” in string to their corresponding HTML entities. Useful for preventing XSS when displaying user-generated content. |
| unescape _.unescape([string=”]) | The inverse of _.escape; converts HTML entities ’&’, ’<’, ’>’, ’”’, and ''' back to their characters. |
| escapeRegExp _.escapeRegExp([string=”]) | Escapes the RegExp special characters ^$.*+?()[]{}| in string. Useful when needing to match literal characters within a regular expression pattern. |
| template _.template([string=”], [options={}]) | Creates a compiled template function that can interpolate data properties into the string. Offers more features than native template literals, like different delimiters and explicit compilation. |
| truncate _.truncate([string=”], [options={}]) | Truncates string if it’s longer than the given maximum length. The last characters of the truncated string are replaced with the omission string which defaults to ”…”. Options allow customization of length, omission string, and separator. |
| words _.words([string=”], [pattern]) | Splits string into an array of its words. Can use a custom regex pattern. |
| deburr _.deburr([string=”]) | Deburrs string by converting Latin-1 Supplement and Latin Extended-A letters to basic Latin letters and removing combining diacritical marks (e.g., ‘déjà vu’ -> ‘deja vu’). |
| parseInt _.parseInt(string, [radix=10]) | Converts string to an integer of the specified radix. Behaves similarly to native parseInt but handles non-string values more gracefully by converting them to strings first. Always recommended to specify the radix. |
Example: Case Conversion and Templating
Section titled “Example: Case Conversion and Templating”import _ from 'lodash-es';
const messyString = '--foo bar BAZ--';const urlSlug = _.kebabCase(messyString);// urlSlug: 'foo-bar-baz'
const variableName = _.camelCase(messyString);// variableName: 'fooBarBaz'
const title = _.startCase(_.lowerCase(messyString));// title: 'Foo Bar Baz'
const user = { name: 'Alice', id: 123 };const templateString = 'User <%- name %> (ID: <%- id %>) logged in.';
// Compile the templateconst compiled = _.template(templateString);
// Execute with dataconst message = compiled(user);// message: 'User Alice (ID: 123) logged in.'
const longText = 'This is a very long string that needs truncation.';const truncated = _.truncate(longText, { 'length': 20 });// truncated: 'This is a very long...'
console.log('URL Slug:', urlSlug);console.log('Variable Name:', variableName);console.log('Title:', title);console.log('Template Message:', message);console.log('Truncated Text:', truncated);Lodash string methods are especially handy for standardizing user input, generating slugs or identifiers, formatting text for display, and basic templating tasks.