← Back to JavaScript, page 9

javascript-0164 · Easy fresher

How do you write common string helpers such as capitalize, title case, truncate, word count, and reverse words?

Most helpers combine split, map, join, slice, and regular expressions. Capitalize with charAt(0).toUpperCase() plus slice(1), split words on whitespace with a regular expression, truncate by length and add an ellipsis that fits in the limit, and count words with match. Handle empty strings and extra whitespace, remember strings are immutable, and mention code points for emoji.

Full answer

These small tasks test knowledge of the string methods and attention to edge cases. Strings are immutable, so every helper returns a new string.

capitalize(text): take the first character, uppercase it, and join it with the rest: text.charAt(0).toUpperCase() + text.slice(1). charAt(0) returns an empty string for an empty input, while text[0] gives undefined, so charAt is safer. For titles, split into words, capitalize each, and join: text.toLowerCase().split(' ').map(capitalize).join(' ').

truncate(text, max): if text.length <= max, return it. Otherwise return text.slice(0, max - 1) + '…' so the result fits in max characters. A better version cuts at the last space before the limit so words are not split. Note that length counts UTF-16 units, so a cut can split an emoji; spread with [...text] for code points.

countWords(text): text.trim().split(/\s+/).filter(Boolean).length works. For an empty string, ''.split(/\s+/) gives [''], so the filter is needed. A regular expression with match(/\S+/g)?.length ?? 0 is another way.

reverseWords(text): text.trim().split(/\s+/).reverse().join(' ').

Other common ones: camelCase and kebab-case conversions with replace and a callback, slugify (lowercase, remove accents with normalize('NFD') and a range replace, replace non-alphanumerics with hyphens), isBlank (!text.trim()), countOccurrences (split(sub).length - 1 or matchAll), and padStart for ids.

Habits that interviewers like: check for non-string input if the function is public, do not mutate arguments, name edge cases (empty string, only spaces, repeated spaces, Unicode), and give the complexity (these are linear in the text length).

javascript
const capitalize = (text) => text.charAt(0).toUpperCase() + text.slice(1);
const titleCase = (text) => text.toLowerCase().split(/\s+/).filter(Boolean).map(capitalize).join(' ');

function truncate(text, max, ellipsis = '\u2026') {
  if (text.length <= max) return text;
  const cut = text.slice(0, max - ellipsis.length);
  const lastSpace = cut.lastIndexOf(' ');
  return (lastSpace > 0 ? cut.slice(0, lastSpace) : cut) + ellipsis;
}

const countWords = (text) => text.trim().split(/\s+/).filter(Boolean).length;
const reverseWords = (text) => text.trim().split(/\s+/).reverse().join(' ');
const camelCase = (text) => text.toLowerCase().replace(/[^a-z0-9]+(.)/g, (_, ch) => ch.toUpperCase());
const kebabCase = (text) => text.replace(/([a-z0-9])([A-Z])/g, '$1-$2').replace(/[\s_]+/g, '-').toLowerCase();
const slugify = (text) => text.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
const countOccurrences = (text, part) => (part ? text.split(part).length - 1 : 0);
const isBlank = (text) => text.trim() === '';

console.log(capitalize('hello'), JSON.stringify(capitalize('')), titleCase('the QUICK  brown fox'));
console.log(truncate('JavaScript interview questions', 20), '|', truncate('short', 20), '|', truncate('Supercalifragilistic', 10));
console.log(countWords('  one  two   three '), countWords(''), countWords('   '), reverseWords('  the sky  is blue '));
console.log(camelCase('hello world-foo_bar'), kebabCase('helloWorld fooBar'), slugify('  Caf\u00e9 Cr\u00e8me: the Best!  '));
console.log(countOccurrences('banana', 'an'), countOccurrences('aaa', 'aa'), countOccurrences('abc', ''), isBlank('  \n'), isBlank(' a '));
console.log(String(7).padStart(3, '0'), 'ab'.padEnd(5, '.') + '|', 'x'.repeat(3));
console.log('emoji cut:', JSON.stringify('a\u{1F600}b'.slice(0, 2)), [...'a\u{1F600}b'].slice(0, 2).join('') === 'a\u{1F600}');

Run with Node.js v24.22.1 as js-164.js; two runs gave identical output. Output: Hello "" The Quick Brown Fox JavaScript… | short | Supercali… 3 0 0 blue is sky the helloWorldFooBar hello-world-foo-bar cafe-creme-the-best 2 1 0 true false 007 ab...| xxx emoji cut: "a\ud83d" true

Key points

  • Strings are immutable; every helper returns a new string.
  • Capitalize with charAt(0).toUpperCase() plus slice(1); title case maps it over words.
  • Truncate so the result including the ellipsis fits the limit; prefer cutting at a word boundary.
  • Count words by splitting on /\s+/ and filtering empty strings, or with match.
  • Handle empty input, extra spaces, and Unicode.

Common mistakes

  • Using text[0].toUpperCase() on an empty string, which throws a TypeError.
  • Counting words with split(' ') and getting wrong counts for repeated spaces.
  • Truncating to the limit and then adding the ellipsis, so the result is too long.
  • Expecting string methods to change the original string.

Follow-ups

  • How would you capitalize the first letter of each sentence?
  • How would you truncate HTML safely?
  • How would you count characters as a person sees them, including emoji?

Tips

  • Ask about empty input and extra spaces before coding.
  • Return new strings and say why.
  • Mention Unicode when you cut or reverse text.