How do I multiply a string by N times in javascript?

0

Good evening, I have a question, I need to enter a number in javascript print it in the console for the amount entered. For example if you want the string to be an asterisk "*": If I enter a number 5, the result should be: *****.

Something that works like this: 5 * "*" = *****

    
asked by Angel 25.05.2017 в 07:48
source

3 answers

4

The str.repeat method will do that for you:

var str = "Hello world!";
str.repeat(2);

Result: Hello world! Hello world!

If you want to multiply numbers it will simply be like a normal multiplication

    
answered by 25.05.2017 в 08:08
0

A workaround very used in your case is to use the join method of the Array object:

function calcularResultado(){
  var caracter = $('#caracter').val();
  var repeticiones = parseInt($('#repeticiones').val());
  if (caracter.length!==1 || isNaN(repeticiones)) { 
    $('#resultado').text = '';
    return; 
  }

  $('#resultado').text(Array(repeticiones + 1).join(caracter));
}

$(function(){
  $('#caracter').on('keyup', calcularResultado);
  $('#repeticiones').on('keyup', calcularResultado);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Carácter: <input id="caracter" type="text" maxlength="1" placeholder="Introduce carácter" /><br /><br />
Número: <input id="repeticiones" type="number" placeholder="Nº de repeticiones" /><br /><br />
<div id="resultado"></div>
    
answered by 25.05.2017 в 08:18
0

I hope this serves you. Greetings.

function Concatenar_String(A_Repetir, Num_Veces)
{
	  for(var i = 0; i < Num_Veces; i ++)
	  {
		    Valor_Final += A_Repetir;
	  } 
	  return Valor_Final;
}
    
answered by 20.11.2017 в 23:56