How to add a number with a string

Asked

Viewed 758 times

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 intended was that var mao3, showed goncalo2 and not goncalo11, how can I do this?

  • To do this you will need to separate the number from your string, there are a thousand ways to do this, what is your main goal with this?

  • I knew, that there was a Function that did this, I just can’t remember which.

  • What are the possible strings? Any input pattern? Numbers in the middle of the string should also be summed?

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);

1

I set up a more comprehensive function that accepts type strings gonc4lo1 and make a sum of these numbers in the middle of the word beyond the 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>

0

Do so:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.