PHP's str_pad in TypeScript

How to use

Install via yarn add locutus and import: import { str_pad } from 'locutus/php/strings/str_pad'.

Or with CommonJS: const { str_pad } = require('locutus/php/strings/str_pad')

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
1str_pad('Kevin van Zonneveld', 30, '-=', 'STR_PAD_LEFT')'-=-=-=-=-=-Kevin van Zonneveld'
2str_pad('Kevin van Zonneveld', 30, '-', 'STR_PAD_BOTH')'------Kevin van Zonneveld-----'

Here's what our current TypeScript equivalent to PHP's str_pad looks like.

export function str_pad(input: string, padLength: number, padString: string, padType: string): string {
// discuss at: https://locutus.io/php/str_pad/
// original by: Kevin van Zonneveld (https://kvz.io)
// improved by: Michael White (https://getsprink.com)
// input by: Marco van Oort
// bugfixed by: Brett Zamir (https://brett-zamir.me)
// example 1: str_pad('Kevin van Zonneveld', 30, '-=', 'STR_PAD_LEFT')
// returns 1: '-=-=-=-=-=-Kevin van Zonneveld'
// example 2: str_pad('Kevin van Zonneveld', 30, '-', 'STR_PAD_BOTH')
// returns 2: '------Kevin van Zonneveld-----'

let half = ''
let padToGo

const _strPadRepeater = function (s: string, len: number): string {
let collect = ''

while (collect.length < len) {
collect += s
}
collect = collect.substr(0, len)

return collect
}

input += ''
padString = padString !== undefined ? padString : ' '

if (padType !== 'STR_PAD_LEFT' && padType !== 'STR_PAD_RIGHT' && padType !== 'STR_PAD_BOTH') {
padType = 'STR_PAD_RIGHT'
}
if ((padToGo = padLength - input.length) > 0) {
if (padType === 'STR_PAD_LEFT') {
input = _strPadRepeater(padString, padToGo) + input
} else if (padType === 'STR_PAD_RIGHT') {
input = input + _strPadRepeater(padString, padToGo)
} else if (padType === 'STR_PAD_BOTH') {
half = _strPadRepeater(padString, Math.ceil(padToGo / 2))
input = half + input + half
input = input.substr(0, padLength)
}
}

return input
}

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


« More PHP strings functions


Star