Python's string.capwords in TypeScript

How to use

Install via yarn add locutus and import: import { capwords } from 'locutus/python/string/capwords'.

Or with CommonJS: const { capwords } = require('locutus/python/string/capwords')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1capwords('kevin van zonneveld')'Kevin Van Zonneveld'
2capwords('HELLO WORLD')'HELLO WORLD'

Here's what our current TypeScript equivalent to Python's string.capwords looks like.

export function capwords(str: string): string {
// discuss at: https://locutus.io/python/capwords/
// original by: Jonas Raoni Soares Silva (https://www.jsfromhell.com)
// improved by: Waldo Malqui Silva (https://waldo.malqui.info)
// improved by: Robin
// improved by: Kevin van Zonneveld (https://kvz.io)
// bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
// input by: James (https://www.james-bell.co.uk/)
// example 1: capwords('kevin van zonneveld')
// returns 1: 'Kevin Van Zonneveld'
// example 2: capwords('HELLO WORLD')
// returns 2: 'HELLO WORLD'

const pattern = /^([a-z\u00E0-\u00FC])|\s+([a-z\u00E0-\u00FC])/g
return (str + '').replace(pattern, function ($1) {
return $1.toUpperCase()
})
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


Help us add more

Got a rainy Sunday afternoon and a taste for a porting puzzle?

We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.

« More Python string functions


Star