How to add a number with a string

0

Well, I have the following code:

<script type="text/javascript">
var mao1 = "goncalo1";
var mao2 = 1;
var mao3 = mao1+mao2;

window.alert(mao3);

</script>

What I wanted was for the var man3, to show goncalo2 and not goncalo11, how can I do that?

    
asked by anonymous 27.03.2017 / 01:31

3 answers

2
var mao1 = "goncalo1";
var mao2 = 1;
var mao1Numero = mao1.replace(/[^0-9]/g,'');
var mao3 =  mao1.replace(/[0-9]/g,'') +  (parseInt(mao1Numero) + mao2);
    
27.03.2017 / 04:02
1

I have built a more comprehensive function that accepts strings of type gonc4lo1 and that sums these numbers in the middle of the word in addition to mao2

function calcular() {
  var mao1 = document.getElementById('mao1').value;
  var mao2 = document.getElementById('mao2').value;
  document.getElementById('resultado').innerHTML = operar(mao1, mao2);
}

function operar(a, b) {
  return a.match(/\D+/g).join('') +  (a.match(/\d+/g).reduce((a, b) => parseInt(a) + parseInt(b), 0) + parseInt(b));
}
<button onclick="calcular()">Calcular</button><br/><br/>
<div id="resultado"></div>
<br/><br/>
mao1: <input id="mao1" type="text"><br/> mao2: 0 <input id="mao2" type="range" max="10" onblur="document.getElementById('valor').innerHTML = '(selecionado '+this.value+')'" value="0"> 10 <span id="valor"><span>
    
27.03.2017 / 17:03
0

Do this:

var mao1 = "Carlos1";
var mao2 = 1;
var mao3 = mao1.replace(/[0-9]/, parseInt(mao1.match(/[0-9]/)) + mao2);
    
27.03.2017 / 07:37