Lodash provides rich string operation methods. Here is a detailed answer about Lodash string operations:
Common Lodash String Operation Methods
1. String Case Conversion
_.camelCase([string=''])
Converts string to camel case.
javascript_.camelCase('Foo Bar'); // => 'fooBar' _.camelCase('--foo-bar--'); // => 'fooBar' _.camelCase('__FOO_BAR__'); // => 'fooBar' // Real application: Convert API response to camel case function convertToCamelCase(obj) { return _.mapKeys(obj, (value, key) => _.camelCase(key)); } const apiResponse = { 'first_name': 'John', 'last_name': 'Doe', 'user_age': 30 }; const camelCaseObj = convertToCamelCase(apiResponse); // => { firstName: 'John', lastName: 'Doe', userAge: 30 }
_.snakeCase([string=''])
Converts string to snake case.
javascript_.snakeCase('Foo Bar'); // => 'foo_bar' _.snakeCase('fooBar'); // => 'foo_bar' _.snakeCase('--foo-bar--'); // => 'foo_bar' // Real application: Convert object keys to snake case for API requests function convertToSnakeCase(obj) { return _.mapKeys(obj, (value, key) => _.snakeCase(key)); } const requestData = { firstName: 'John', lastName: 'Doe', userAge: 30 }; const snakeCaseObj = convertToSnakeCase(requestData); // => { first_name: 'John', last_name: 'Doe', user_age: 30 }
_.kebabCase([string=''])
Converts string to kebab case.
javascript_.kebabCase('Foo Bar'); // => 'foo-bar' _.kebabCase('fooBar'); // => 'foo-bar' _.kebabCase('__FOO_BAR__'); // => 'foo-bar' // Real application: Generate CSS class names function generateClassName(baseName, modifiers) { const base = _.kebabCase(baseName); return modifiers.map(mod => `${base}--${_.kebabCase(mod)}`).join(' '); } const className = generateClassName('userCard', ['active', 'large']); // => 'user-card--active user-card--large'
_.upperFirst([string=''])
Converts the first character of string to upper case.
javascript_.upperFirst('fred'); // => 'Fred' _.upperFirst('FRED'); // => 'FRED' // Real application: Format user names function formatUserName(name) { return _.upperFirst(_.toLower(name)); } console.log(formatUserName('john')); // => 'John' console.log(formatUserName('JOHN')); // => 'John'
_.lowerFirst([string=''])
Converts the first character of string to lower case.
javascript_.lowerFirst('Fred'); // => 'fred' _.lowerFirst('FRED'); // => 'fRED'
_.startCase([string=''])
Converts string to start case.
javascript_.startCase('--foo-bar--'); // => 'Foo Bar' _.startCase('fooBar'); // => 'Foo Bar' _.startCase('__FOO_BAR__'); // => 'FOO BAR' // Real application: Format titles function formatTitle(title) { return _.startCase(title); } console.log(formatTitle('hello-world')); // => 'Hello World' console.log(formatTitle('user_profile')); // => 'User Profile'
2. String Truncation and Padding
_.truncate([string=''], [options={}])
Truncates string, adding ellipsis.
javascript_.truncate('hi-diddly-ho there, neighborino'); // => 'hi-diddly-ho there, neighbo...' _.truncate('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': ' ' }); // => 'hi-diddly-ho there,...' _.truncate('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': /,? +/ }); // => 'hi-diddly-ho there...' _.truncate('hi-diddly-ho there, neighborino', { 'omission': ' [...]' }); // => 'hi-diddly-ho there, neig [...]' // Real application: Truncate article summary function truncateText(text, maxLength = 100) { return _.truncate(text, { length: maxLength, separator: ' ', omission: '...' }); } const article = 'This is a long article that needs to be truncated for display purposes...'; const summary = truncateText(article, 50); // => 'This is a long article that needs to be...'
_.pad([string=''], [length=0], [chars=' '])
Pads string on both sides with characters.
javascript_.pad('abc', 8); // => ' abc ' _.pad('abc', 8, '_-'); // => '_-abc_-_' _.pad('abc', 3); // => 'abc'
_.padStart([string=''], [length=0], [chars=' '])
Pads string on the left side with characters.
javascript_.padStart('abc', 6); // => ' abc' _.padStart('abc', 6, '_-'); // => '_-_abc' _.padStart('abc', 3); // => 'abc' // Real application: Format numbers function formatNumber(num, length = 6) { return _.padStart(String(num), length, '0'); } console.log(formatNumber(42)); // => '000042' console.log(formatNumber(123456)); // => '123456'
_.padEnd([string=''], [length=0], [chars=' '])
Pads string on the right side with characters.
javascript_.padEnd('abc', 6); // => 'abc ' _.padEnd('abc', 6, '_-'); // => 'abc-_-' _.padEnd('abc', 3); // => 'abc'
3. String Splitting and Joining
_.split([string=''], [separator], [limit])
Splits string into an array.
javascript_.split('a-b-c', '-', 2); // => ['a', 'b'] _.split('a-b-c', '-'); // => ['a', 'b', 'c'] // Real application: Parse paths function parsePath(path) { return _.split(path, '/').filter(Boolean); } console.log(parsePath('/users/123/posts')); // => ['users', '123', 'posts']
_.words([string=''], [pattern])
Splits string into an array of words.
javascript_.words('fred, barney, & pebbles'); // => ['fred', 'barney', 'pebbles'] _.words('fred, barney, & pebbles', /[^, ]+/g); // => ['fred', 'barney', '&', 'pebbles'] // Real application: Count words function countWords(text) { return _.words(text).length; } console.log(countWords('Hello world, this is a test')); // => 6
4. String Cleaning
_.trim([string=''], [chars=whitespace])
Removes leading and trailing whitespace from string.
javascript_.trim(' abc '); // => 'abc' _.trim('-_-abc-_-', '_-'); // => 'abc' // Real application: Clean user input function cleanInput(input) { return _.trim(input); } console.log(cleanInput(' john@example.com ')); // => 'john@example.com'
_.trimStart([string=''], [chars=whitespace])
Removes leading whitespace from string.
javascript_.trimStart(' abc '); // => 'abc ' _.trimStart('-_-abc-_-', '_-'); // => 'abc-_-'
_.trimEnd([string=''], [chars=whitespace])
Removes trailing whitespace from string.
javascript_.trimEnd(' abc '); // => ' abc' _.trimEnd('-_-abc-_-', '_-'); // => '-_-abc'
_.deburr([string=''])
Removes diacritical marks from string.
javascript_.deburr('déjà vu'); // => 'deja vu' _.deburr('Juan José'); // => 'Juan Jose' // Real application: Create search-friendly strings function createSearchString(text) { return _.deburr(_.toLower(text)); } console.log(createSearchString('Café au Lait')); // => 'cafe au lait'
5. String Repetition
_.repeat([string=''], [n=1])
Repeats string n times.
javascript_.repeat('*', 3); // => '***' _.repeat('abc', 2); // => 'abcabc' _.repeat('abc', 0); // => '' // Real application: Create separator lines function createSeparator(char = '-', length = 50) { return _.repeat(char, length); } console.log(createSeparator('=', 30)); // => '=============================='
6. String Templates
_.template([string=''], [options={}])
Creates a compiled template function.
javascript// Use default "interpolate" delimiter var compiled = _.template('hello <%= user %>!'); compiled({ 'user': 'fred' }); // => 'hello fred!' // Use HTML "escape" delimiter var compiled = _.template('<b><%- value %></b>'); compiled({ 'value': '<script>' }); // => '<b><script></b>' // Use "evaluate" delimiter var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>'); compiled({ 'users': ['fred', 'barney'] }); // => '<li>fred</li><li>barney</li>' // Use custom delimiters var compiled = _.template('<% if (value) { %>Yes<% } else { %>No<% } %>', { 'imports': { 'value': true } }); compiled(); // => 'Yes' // Real application: HTML templates function createTemplate(templateString) { return _.template(templateString); } const userTemplate = createTemplate(` <div class="user-card"> <h2><%= name %></h2> <p>Email: <%= email %></p> <p>Age: <%= age %></p> </div> `); const html = userTemplate({ name: 'John Doe', email: 'john@example.com', age: 30 });
7. String Checking
_.endsWith([string=''], [target], [position=string.length])
Checks if string ends with the given target string.
javascript_.endsWith('abc', 'c'); // => true _.endsWith('abc', 'b'); // => false _.endsWith('abc', 'b', 2); // => true // Real application: Check file extensions function hasExtension(filename, extension) { return _.endsWith(filename, '.' + extension); } console.log(hasExtension('document.pdf', 'pdf')); // => true console.log(hasExtension('image.jpg', 'png')); // => false
_.startsWith([string=''], [target], [position=0])
Checks if string starts with the given target string.
javascript_.startsWith('abc', 'a'); // => true _.startsWith('abc', 'b'); // => false _.startsWith('abc', 'b', 1); // => true // Real application: Check URL protocols function isSecureUrl(url) { return _.startsWith(url, 'https://'); } console.log(isSecureUrl('https://example.com')); // => true console.log(isSecureUrl('http://example.com')); // => false
8. String Replacement
_.replace([string=''], pattern, replacement)
Replaces matches for pattern in string with replacement.
javascript_.replace('Hi Fred', 'Fred', 'Barney'); // => 'Hi Barney' // Real application: Replace template variables function replaceTemplate(template, data) { let result = template; _.forOwn(data, (value, key) => { result = _.replace(result, new RegExp(`{{${key}}}`, 'g'), value); }); return result; } const template = 'Hello {{name}}, your order {{orderId}} is ready.'; const result = replaceTemplate(template, { name: 'John', orderId: '12345' }); // => 'Hello John, your order 12345 is ready.'
Real-World Application Examples
URL Parameter Processing
javascriptclass URLHelper { static buildQuery(params) { return _.chain(params) .pickBy(value => value != null) .mapValues(value => String(value)) .toPairs() .map(([key, value]) => `${_.kebabCase(key)}=${encodeURIComponent(value)}`) .join('&') .value(); } static parseQuery(queryString) { return _.chain(queryString) .split('&') .filter(Boolean) .map(pair => pair.split('=')) .fromPairs() .mapValues(value => decodeURIComponent(value)) .mapKeys(key => _.camelCase(key)) .value(); } } const params = { userId: 123, sortOrder: 'desc', pageSize: 10 }; const queryString = URLHelper.buildQuery(params); // => 'user-id=123&sort-order=desc&page-size=10' const parsedParams = URLHelper.parseQuery(queryString); // => { userId: '123', sortOrder: 'desc', pageSize: '10' }
Filename Processing
javascriptclass FileNameHelper { static sanitize(filename) { return _.chain(filename) .deburr() .replace(/[^\w\s-]/g, '') .trim() .replace(/[-\s]+/g, '-') .toLower() .value(); } static getExtension(filename) { const parts = _.split(filename, '.'); return parts.length > 1 ? _.last(parts) : ''; } static getBaseName(filename) { const parts = _.split(filename, '.'); return parts.length > 1 ? _.initial(parts).join('.') : filename; } } const filename = 'My Document (Final).pdf'; const sanitized = FileNameHelper.sanitize(filename); // => 'my-document-final.pdf' const extension = FileNameHelper.getExtension(sanitized); // => 'pdf' const baseName = FileNameHelper.getBaseName(sanitized); // => 'my-document-final'
Text Formatting
javascriptclass TextFormatter { static toTitleCase(text) { return _.startCase(_.toLower(text)); } static truncate(text, maxLength) { return _.truncate(text, { length: maxLength, separator: ' ', omission: '...' }); } static slugify(text) { return _.chain(text) .deburr() .toLower() .replace(/[^\w\s-]/g, '') .trim() .replace(/[-\s]+/g, '-') .value(); } static capitalizeWords(text) { return _.chain(text) .split(' ') .map(_.upperFirst) .join(' ') .value(); } } const text = 'hello world, this is a test'; console.log(TextFormatter.toTitleCase(text)); // => 'Hello World, This Is A Test' console.log(TextFormatter.truncate(text, 20)); // => 'hello world, this...' console.log(TextFormatter.slugify('Hello World!')); // => 'hello-world' console.log(TextFormatter.capitalizeWords('hello world')); // => 'Hello World'
Summary
Lodash provides rich string operation methods covering string case conversion, truncation and padding, splitting and joining, cleaning, repetition, templates, checking, and replacement. Mastering these methods can greatly improve the efficiency of string processing and code readability. In actual development, it's recommended to choose appropriate methods based on specific needs and make full use of method chaining to simplify code.