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