How to add the numerical part ONLY to one digit?

1

var a = "20px";

setInterval(function(){

a += 20;
console.log(a);
},1000);

How would you add only the numerical part? , since with my code it remains as string

    
asked by Eduardo Sebastian 19.08.2017 в 04:59
source

3 answers

1

With parseInt you can achieve it:

var a = "20px"; 

setInterval(function(){ 
a = (parseInt(a) + 20) + "px"; 
console.log(a); 
},1000);

According to the documentation :

  

If parseInt finds a character that is not a numeral in the base   specified, ignores it and all successive characters and returns the   entire value analyzed up to that point. parseInt truncates the numbers to   whole values. Initial and final spaces are allowed.

In other words, it will analyze the string "10px" and when it finds the character "p" it will stop and return the first characters that are digits, in this case 10, as inte [ger.

    
answered by 19.08.2017 / 15:33
source
0

You can try cutting the chain, as long as you know what text will come inside.

Then you convert the whole or floating number depending on what you need, and you do your operation.

Ex.

var tamanio = '20px';
var cantidad = tamanio.split("px");
var suma = parseInt(cantidad[0])+10;

console.log(suma);
    
answered by 19.08.2017 в 05:13
0

EDIT

Since you want to keep the two values, a simple replace would suffice to get each value separately.

Then you can convert the result numero to integer using the unary operator + (or through another method) and do the addition.

var string = "20px";
var numero = string.replace(/\D/g, "");
var letras = string.replace(/[^a-z]/gi, "");   

document.write("Número extraido: "+numero+"<br>");
document.write("Texto extraido: "+letras+"<br>");
var a = +numero+20;
document.write("Suma: "+a);
    
answered by 19.08.2017 в 06:11