• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Miscellaneous / Add characters to the beginning of a string if it’s less than a certain length

Add characters to the beginning of a string if it’s less than a certain length

Add characters to the beginning of a string if it’s less than a certain length

Add characters to the beginning of a string if it’s less than a certain length. Accepts two arguments: the length the string should be, and what characters to add if it’s not that length. The characters to use is optional, and defaults to a space ().

// Add a leading zero for hours below 10
var hour3 = '3';
var hour12 = '12';

// returns "03"
hour3.padStart(2, '0');

// returns "12"
hour12.padStart(2, '0');

Source

https://vanillajstoolkit.com/reference/strings/string-padstart/

Miscellaneous

Related Snippets:

  • Remove leading and trailing whitespace from a string
  • Confirm Yes or No With JavaScript
  • Capitalize the first letter of every word in a string
  • How to Check if an Array Includes a Value in JavaScript

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers