Sean Cook Sean Cook - 1 year ago 111
Javascript Question

Alternate adding a character to the beginning and end of string

I am trying to solve a Javascript puzzle. I need to write a function that uses a while loop to add a character to the beginning of string and then on the next loop adds the character to the end of the string and to the beginning on the loop after that. The function takes two parameters a string and a number of characters to add.
So far I have

function padIt(str,n){
//coding here
var newStr = "";
var padding = "*";
var i = 0;

if (i%2===0){
newStr = newStr+padding;
} else{
newStr = padding+str;
return newStr;

I am passing the first two test cases but it won't work properly for the third time through the loop. Expecting "* * a *" for n = 3 but only getting "*a". It has to be a while loop so I don't know if I am not setting the loop up correctly or if I am messing up the variables. Any help is greatly appreciated as I am totally lost.

Answer Source

You can do it by writing code like below,

function padIt(str,n, pad = "*"){
  var left = Math.ceil(n/2), right = n - left;
  return pad.repeat(left) + str + pad.repeat(right);

And this function would print,

console.log("a", 1); // "*a"
console.log("a", 2); // "*a*"
console.log("a", 10); // "*****a*****"

Thing need to be read after implementing this code,

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download