0

I have a string

var str = 'string'

I have a multiplier

var mult = 3

I want to return stringstringstring

The mult will change. Basically mult is kind of like a power but this is a string not a number. And I need to return multiple strings. I'm thinking of looping where mult = the number of times to loop and each would conceptually 'push' but I don't want an array or something like =+ but not a number. I'm thinking I could have the output push to an array the number of times = to mult, and then join the array - but I don't know if join is possible without a delimiter. I'm new at javascript and the below doesn't work but it's what I'm thinking. There's also no ability to input a function in the place I'm running javascript and also no libraries.

var loop = {
  var str = 'string'
  var arr = [];
  var mult = 3;
  var i = 0
  for (i = 0, mult-1, i++) {
    arr.push('string'[i]);
  }
}
var finalString = arr.join(''); // I don't know how to get it out of an object first before joining

Not sure if what I want is ridiculous or if it's at all possible

4 Answers 4

2

You mean something like below,

var str = 'string'
var mult = 3
var str2 = ''
for(i = 0; i < mult; i++) {
    str2 += str
}
console.log(str2)

Sign up to request clarification or add additional context in comments.

Comments

2

var str = 'string'
var mult = 3;
var sol =""
while(mult--) {
   sol +=str;
}
console.log(sol)

Using resusable function:

const concatStr= (str, mult)=>{
  var sol =""
  while(mult--) {
 sol +=str;
  }
  console.log(sol)
}

concatStr("string",3)

Using the inbuilt Array.from method:

var str = "string"
var mult = 3
var sol = Array.from({length: mult}, ()=> str).join("")
console.log(sol)

Comments

1

function concatString(str, mult) {
   var result = ''
   for(i = 0; i < mult; i++) {
      result = result.concat(str);
   }
    return result;
 }

const value = concatString('string', 3);
console.log(value);

Also you can use array inbuilt methods,

const mult = 3, displayVal = 'str';
Array(mult).fill(displayVal).join('');

Comments

0

// the string object has a repeat method
console.log('string'.repeat(3));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.