es-toolkit/docs/reference/string/pad.md

35 lines
784 B
Markdown
Raw Normal View History

2024-09-03 17:14:53 +03:00
# pad
Pads string on the left and right sides if it's shorter than length. Padding characters are truncated if they can't be evenly divided by length.
If the length is less than or equal to the original string's length, or if the padding character is an empty string, the original string is returned unchanged.
## Signature
```typescript
2024-09-03 17:28:44 +03:00
function pad(str: string, length: number, chars = ' '): string;
2024-09-03 17:14:53 +03:00
```
## Parameters
- `str` (`string`): The string to pad.
2024-09-03 17:28:44 +03:00
- `length` (`number`): The length of the resulting string.
2024-09-03 17:14:53 +03:00
- `char` (`string`): The character to pad the string with. Defaults to `' '`.
## Returns
2024-09-03 17:28:44 +03:00
(`string`): Returns the padded string.
2024-09-03 17:14:53 +03:00
## Example
```javascript
pad('abc', 8);
// => ' abc '
pad('abc', 8, '_-');
// => '_-abc_-_'
pad('abc', 3);
// => 'abc'
```