0
    function space(str, numspace)
   {
       output="";
       for(i=0;i<str.length;++i)
       {
           output = numspace+ str;
       }
       for(i=0;i<str.length;++i)
       {
           output = output + numspace;
       }
       return output;
   }

I am trying to get this function to add an equal amount of whitespace to both ends of the string. I am not allowed to use built-in functions so that explains why i'm doing this the long way.

The output I get with the code I have :

space("hello","--")

"--hello-----------"

The "-" signify spaces, so the amount of spaces on the left side of the string is correct, but the amount of spaces on the right side of the string is way to much. Anyone have any ideas why this is occuring?

Tiago Sa
  • 87
  • 1
  • 6

4 Answers4

1

Why not do this instead:

const space = (str, numspace) => {
    const spc = Array(numspace).fill(' ').join('')
    return spc+str+spc
}

console.log(space("ap", 3))

What it does:

  • Create a spc variable which has as many spaces as numspace demands
  • Join spc on both sides of str

Edit - The longer way

const space = (str, numspace) => {
    let spc = ''
    for (;numspace--;spc+=' '){}
    return spc+str+spc
}

console.log(space('ap',3))
Arnav Thorat
  • 3,078
  • 3
  • 8
  • 33
AP.
  • 8,082
  • 2
  • 24
  • 33
0

If numspace is an integer, then you can use that value as the upper boundary in a for loop like so:

function space(str, numspace)
{
    var emptySpace = "";
    for (i = 0; i < numspace; i++){
        emptySpace += " ";
    }
    var output = emptySpace + str + emptySpace;
    return output;
}

console.log("'" + space('example1', 5) + "'");
console.log("'" + space('example2', 3) + "'");
console.log("'" + space('example3', 1) + "'");

This way you'll create a variable emptySpace that is a string numspace in length of white space and attach it to the front and back of the str string before returning the output.

EDIT: Based on information from the comments of OP I have changed the function.

DibsyJr
  • 854
  • 7
  • 18
0

Just surround it with anything that you want to have in both side.

  function space(str, numspace)
   {
       output=str;
       for(i=0;i<str.length;++i)
       {
           output = numspace + output + numspace;
       }
       return output;
   }
Soley
  • 1,716
  • 1
  • 19
  • 33
0

This function can be used to append any number of characters to the text

    var output = addSpace('hello','*',4);
    alert(output); // output ****hello****

    function addSpace(text,character,no){
        var appendChar = character;
        for(var i=1;i<no;i++) {
        appendChar = appendChar+character;
      }
      return appendChar+text+appendChar;
    }
Haseena P A
  • 16,858
  • 4
  • 18
  • 35