padStart
string
Pads string on the left side if it's shorter than length. Padding characters are truncated if they exceed length.
Installation
Import
import { padStart } from '@tulx/utils';Source Code
Implementation
/**
* Pads string on the left side if it's shorter than length.
* Padding characters are truncated if they exceed length.
*
* @param string - The string to pad.
* @param length - The padding length.
* @param chars - The string used as padding.
* @returns Returns the padded string.
*
* @example
* ```ts
* padStart('abc', 6); // ' abc'
* padStart('abc', 6, '_-'); // '_-_abc'
* padStart('abc', 3); // 'abc'
* ```
*/
export function padStart(
string: string,
length: number,
chars: string = ' '
): string {
const strLength = string.length;
if (strLength >= length) {
return string;
}
const padLength = length - strLength;
const padChars = chars
.repeat(Math.ceil(padLength / chars.length))
.slice(0, padLength);
return padChars + string;
}
Example
import { padStart } from '@tulx/utils';
padStart('abc', 6); // ' abc'
padStart('abc', 6, '_-'); // '_-_abc'
padStart('abc', 3); // 'abc'Related Functions
camelCase
Converts string to camel case.
capitalize
Converts the first character of string to upper case and the remaining to lower case.
deburr
Deburrs string by converting Latin-1 Supplement and Latin Extended-A letters to basic Latin letters and removing combining diacritical marks.
endsWith
Checks if string ends with the given target string.
escape
Converts the characters "&", "<", ">", '"', and "'" in string to their corresponding HTML entities.
escapeRegExp
Escapes the RegExp special characters "^", "$", "\", ".", "*", "+", "?", "(", ")", "[", "]", "{", "}", and "|" in string.