javascriptstringhumanize

Humanize a string in JavaScript


How do I humanize a string? Based on the following criteria:

  • Deletes leading underscores, if any.
  • Replaces underscores with spaces, if any.
  • Capitalizes the first word.

For example:

this is a test -> This is a test
foo Bar Baz    -> Foo bar baz
foo_bar        -> Foo bar
foo_bar_baz    -> Foo bar baz
foo-bar        -> Foo-bar
fooBarBaz      -> FooBarBaz

Solution

  • Best is indeed to use some regexes:

    ^[\s_]+|[\s_]+$ catches 1 or more white-space characters or underscores either at the very beginning (^) or at the very end ($) of the string. Note that this also catches new-line characters. Replace them with an empty string.

    [_\s]+ Again catches 1 or more white-space characters or underscores, since the ones at the beginning/end of the string are gone, replace with 1 space.

    ^[a-z] Catch a lowercase letter at the beginning of the string. Replace with the uppercase version of the match (you need a callback function for that).

    Combined:

    function humanize(str) {
      return str
          .replace(/^[\s_]+|[\s_]+$/g, '')
          .replace(/[_\s]+/g, ' ')
          .replace(/^[a-z]/, function(m) { return m.toUpperCase(); });
    }
    
    document.getElementById('out').value = [
      '    this is a test',
      'foo Bar Baz',
      'foo_bar',
      'foo-bar',
      'fooBarBaz',
      '_fooBarBaz____',
      '_alpha',
      'hello_ _world,   how    are________you?  '
    ].map(humanize).join('\n');
    textarea { width:100%; }
    <textarea id="out" rows="10"></textarea>