Pad string

2 snippets across 2 stacks - JavaScript, SQL

JSJavaScript

Padding Strings

JS · Strings
Syntax
str.padStart(targetLength, padChar)
str.padEnd(targetLength, padChar)
Example
const orderNum = "42";
console.log(orderNum.padStart(6, "0"));  // "000042"

const label = "Price";
console.log(label.padEnd(12, "."));      // "Price......."

Note Useful for formatting IDs, aligning columns in console output, or zero-padding numbers.

SQLSQL

LPAD / RPAD

SQL · String Functions
Syntax
LPAD(string, target_length, pad_char)
RPAD(string, target_length, pad_char)
Example
SELECT
  LPAD(CAST(invoice_number AS VARCHAR), 8, '0') AS padded_invoice,
  RPAD(product_code, 10, '.') AS padded_code
FROM invoices;
Output
-- padded_invoice | padded_code
-- 00004271       | PRD-42....

Note LPAD pads on the left, RPAD on the right. If the string is already longer than target_length, it gets truncated to target_length. Commonly used for formatting invoice numbers, report columns, and display output.

Frequently asked questions

How do you pad string?
This task is covered in 2 stacks on this page: JavaScript, SQL. The "Padding Strings" snippet in JavaScript uses `str.padStart(targetLength, padChar)`.
Which code does the JavaScript example use?
The "Padding Strings" snippet uses `str.padStart(targetLength, padChar)`, from the Strings section of the JavaScript cheat sheet.
Which stacks cover "pad string" on this page?
JavaScript, SQL. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Padding Strings": Useful for formatting IDs, aligning columns in console output, or zero-padding numbers.