TransWikia.com

Is there a way to make JavaScript read strings as strings when multipying by numbers?

Stack Overflow Asked by PythonCreator on October 1, 2020

I am (using JavaScript) trying to get an output of 50 dashes as a banner like this:

"————————————————–"

I have so far tried the following:

let a = []
for (var i = 0; i < 50; i++) {
  a.push("-")
}

console.log(...a)

and

console.log("-" * 50)

These do not work, as in the first one, there are spaces in between the dashes.
The second one returns NaN, which is not what I need either.

The regular way I used to do this in Python was:

print("-" * 50)

This gave the perfect result of "—————————————————-".

The print() function being Python’s equivalent of console.log().

However, this does not work in JavaScript, as said before.

I also figured out that this does not work due to the fact that the string is parsed as a number.

Is there a way to achieve the "—————————————————-" banner in JavaScript without typing it manually, or is there a way to make sure that "-" is not parsed as a number?

3 Answers

No, javascript lack of that feature. But you could use repeat() on ECMAScript6:

console.log("-".repeat(50))

This is Mozilla's reference https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/String/repeat

Correct answer by Cristian Torres on October 1, 2020

if you want to use an Array:

let a = Array(50).fill('-').join('')

console.log(a)

Answered by Mister Jojo on October 1, 2020

let a = []
for (var i = 0; i < 50; i++) {
  a.push("-")
}

a=a.toString();

a=a.replace(/,/g,'');
console.log(a);

Answered by DCR on October 1, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP