Skip to content

How to add characters to the beginning or end of a string

In this post, you will learn how to add characters to the beginning and end of a string when it’s less than a certain length.

We gonna use string.padEnd() and string.padStart() functions to add extra characters to the end or to the beginning of a string.

string.padStart()

The padStart() method pads the current string with another string (repeated, if needed) so that the resulting string reaches the given length. The padding is applied from the start (left) of the current string.

Syntax:

padStart(targetLength) 
padStart(targetLength, padString)

Examples:

'1234'.padStart(8,'0'); // "00001234"
'abc'.padStart(10);         // "       abc"
'abc'.padStart(10, "foo");  // "foofoofabc"
'abc'.padStart(6,"123465"); // "123abc"
'abc'.padStart(8, "0");     // "00000abc"
'abc'.padStart(1);          // "abc"

string.padEnd()

The padEnd() method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end (right) of the current string.

Syntax:

padEnd(targetLength)
padEnd(targetLength, padString)

Examples:

'abc'.padEnd(5,'*'); // "abc**"
'abc'.padEnd(10);          // "abc       "
'abc'.padEnd(10, "foo");   // "abcfoofoof"
'abc'.padEnd(6, "123456"); // "abc123"
'abc'.padEnd(1);           // "abc"
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments