String Pad in JavaScript

Tram Ho

This article I will introduce padStart and padEnd and some information about them.

1. Syntax

The syntax of String Pad is quite simple:

2. Understanding the Parameters

The padEnd and padStart both take the same parameters

2.1. targetLength

Length of the resulting string when str currently gets pad . If the length of str greater than targetLength , the result is str (unchanged).

Note: targetLength not the number of times str is pad

2.2. padString

padString is the string used to pad current. If the padString is not set, it will default to " " (U + 0020 ‘SPACE’).

If you pass empty string , it will do nothing: v

If padString long resulting in a return dài than targetLength , it will be truncated from cuối to đầu of padString .

How it handles other data types

As mentioned above, the type of the second parameter passed is string . However, you can still pass a value of another type, which will automatically convert to a string via the toString()

The above is the result of toString() for some data types.

Handling undefined

Interestingly, when you convert undefined to a string with toString , you’ll get a TypeError error:

However, if you pass undefined like padString then you won’t get an error:

Why? As far as spec:

ECMAScript Spec If fillString is undefined, let filler be the String value consisting solely of the code unit 0x0020 (SPACE).

=> When you pass a value other than undefined (of course, different from the string ) it will automatically convert the passed value to a string through the toString()

Use Case

Tabular Formatting with padEnd

One of the most commonly used string pad applications is formatting

Right Aligning String with padStart

Align left / right with padStart and padEnd without using css

The result will be:

Receipt formatting

You can also justify both sides of the text (still not use css )

Result:

Masking Numbers

Another application of it is masking number , understood simply to hide some elements of a sequence of numbers (usually card number ).

Browser Support

padStart and padEnd were introduced at the same time and it supports the same browsers – all browsers except Internet Explorer

Browser
Chrome
Firefox
Safari
Edge
Internet Explorer

Reference

https://www.samanthaming.com/tidbits/97-string-padstart-padend/

Share the news now

Source : Viblo