The syntax of the padStart()
method is:
str.padStart(targetLength, padString)
Here, str
is a string.
padStart() Parameters
The padStart()
method takes in:
- targetLength - The length of the final string after current string has been padded. For targetLength < str.length, the string is returned unmodified.
- padString (optional) - The string to pad current string with. Its default value is
" "
.
Note: If padString is too long, it will be truncated from the end to meet targetLength.
Return value from padStart()
- Returns a String of the specified targetLength with padString applied from the start.
Example: Using padStart()
let string = "CODE";
value1 = string.padStart(10);
console.log(value1); // " CODE"
value2 = string.padStart(10, "*");
console.log(value2); // "******CODE"
// long string is truncated
value3 = string.padStart(10, "ABCDEFGHIJKL");
console.log(value3); // "ABCDEFCODE"
function fixedLength(num, len) {
return num.toString().padStart(len, 0);
}
price = fixedLength(5000, 6);
console.log("$" + price); // "$005000"
Output
CODE ******CODE ABCDEFCODE $005000
Recommended Reading: JavaScript String padEnd()