to-caption

Converts camelCase, PascalCase and delimited strings to captions

Visit To Caption for more information.

Status

Release Published What it adds
1.2.0 NPM, 2026 the current release: require('to-caption') returns the function; types for both import and require; titlecase splits on dots; null options accepted
1.1.3 NPM, 2019 the all-uppercase option

Source: github.com/Flamenco/to-caption ยท License: MIT

Install

npm install --save to-caption

Usage

ES module

import toCaption from 'to-caption'

toCaption('helloWorld') // 'Hello World'

CommonJS

const toCaption = require('to-caption')

toCaption('helloWorld') // 'Hello World'

This form needs 1.2.0 or later. Release 1.1.3 ships only the ES module, so require gives the module object rather than the function.

Browser

The package includes a UMD build at dist/toCaption.js, which defines window.toCaption

<script src="https://unpkg.com/to-caption/dist/toCaption.js"></script>
<script>
  console.log(toCaption('helloWorld'))
</script>

Rules

  • Delimiters are period, dash and underscore
  • Leading, trailing and repeated delimiters are ignored
  • Each delimiter becomes a single space, and the character after it is uppercased
  • The first character is uppercased
  • Uppercase letters are prefixed with spaces
  • Any other character, such as a slash or a space, is kept as it is

Samples

Input Caption Note
this.is.a.test This Is A Test
foo Foo
foobar Foobar
fooBar Foo Bar camelCase
FooBar Foo Bar PascalCase
foo_bar Foo Bar
foo.bar Foo Bar
foo-bar Foo Bar
thisIsATest This Is A Test consecutive capitals each start a word
foo/bar Foo/bar slash is not a delimiter
_foobar Foo Bar outer delimiters are dropped
--foo--bar-- Foo Bar repeats count once
FOOBAR F O O B A R see onAllUppercase

Options

The second argument is optional, and may be undefined or null

onAllUppercase

toCaption('HELLO_WORLD', { onAllUppercase: 'titlecase' }) // 'Hello World'

Sets what happens to a string with no lowercase letters

Value HELLO_WORLD becomes
'keep' HELLO_WORLD, unchanged
'titlecase' Hello World
'default', undefined, null or anything else H E L L O W O R L D

Before 1.2.0, 'titlecase' split only on dashes and underscores, so HELLO.WORLD became Hello.world.

TypeScript

Declarations are included. The options type is exported as ToCaptionOptions

import toCaption, { ToCaptionOptions } from 'to-caption'

const options: ToCaptionOptions = { onAllUppercase: 'keep' }
toCaption('HTTP', options) // 'HTTP'

ToCaptionOptions is exported from 1.2.0 on.