str_pad PHP function in JavaScript

Introduction to str_pad

Many times one needs to fill a string with another string using JavaScript. To achieve this, there is a useful function in PHP called str_pad. This function can pad a string to a certain length with another string. In this way, we are able to achieve that a certain data has always the same length, e.g.:

echo str_pad('20', 6, '0', STR_PAD_LEFT);
echo str_pad('1', 6, '0', STR_PAD_LEFT);
echo str_pad('567', 6, '0', STR_PAD_LEFT);
echo str_pad('4589', 6, '0', STR_PAD_LEFT);

//Result:
//000020
//000001
//000567
//004589

str_pad JavaScript implementation

Normally to achieve this in JavaScript, many of us used a for loop like the next one:

function str_pad(str, pad_length, pad_string, pad_type){
  	
	var len = pad_length - str.length;

	if(len < 0) return str;

	for(var i = 0; i < len; i++){

		if(pad_type == "STR_PAD_LEFT"){

			str = pad_string + str;

		}else{

			str += pad_string;

		}

	}

	return str;

}

Array Object

But it is possible to achieve this in an easier way. Using the Array object this process will be faster and we can rid off the for loop.

An Array could be instantiated in different ways:

// Create an empty Array
var my_array = new Array();
var my_array = [];

// Create an Array with elements
var my_array = new Array("a", "b", "c");
var my_array = ["a", "b", "c"];

// Create an empty Array with an specific length
var my_array = new Array(3);

Array join method

Having the Array instantiated, we can use the join method to join all its elements using a custom String parameter as a separator and return the String of this join:

var my_array = ["a", "b", "c"];
var my_string = my_array.join("-");
console.log(my_string);

//Result "a-b-c"

Final function

Knowing this, if we can create an empty Array with a specific length and next using the join method to join its elements using as a separator parameter a String, it is possible to repeat this String multiple times (the length of the array minus 1):

function str_pad(str, pad_length, pad_string, pad_type){

	var len = pad_length - str.length;

	if(len < 0) return str;
  	
	var pad = new Array(len + 1).join(pad_string);
    
	if(pad_type == "STR_PAD_LEFT") return pad + str;
    
	return str + pad;

}

Using the function

console.log str_pad("20", 6, "0", "STR_PAD_LEFT");
console.log str_pad("1", 6, "0", "STR_PAD_LEFT");
console.log str_pad("567", 6, "0", "STR_PAD_LEFT");
console.log str_pad("4589", 6, "0", "STR_PAD_LEFT");

//Result:
//000020
//000001
//000567
//004589
(2 votes, average: 3.00 Out Of 5)
Share this post:

It is possible to insert code fragments between <pre></pre> tags and HTML or XML code between <xmp></xmp> tags.

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.