Ignore certain characters in an innerHTML so I can use parseInt

382 views Asked by At

I'm trying to copy the contents of an innerHTML on a webpage and calculate a number, then add that to the innerHTML, but they contain a $ which is messing up the calculation.

 var x = document.getElementsByClassName("item");
    var i;
    var counter;

    for (i = 0; i < x.length; i++) {
        counter += parseInt(x[i].innerHTML, 10);
        var j = Math.floor(counter/2.15); 
        x[i].innerHTML += (" " + j +"K");
    }


<div class="item">$25.00</div>

An example of the innerHTML would be $25.00 and I want to take that value and divide it by 2.15 and put it after the $25.00. EX: $25.00 11K

This code returns NaNK because the dollar sign ($), what can I do to make it be ignored or removed so the calculation can work? Also, I might not be using parseInt right.

3

There are 3 answers

0
Deep On BEST ANSWER

You need to get a string containing only numerical value first for that remove the character $ using a regex.

var x = document.getElementsByClassName("item");
    var i;
    var counter = 0;

    for (i = 0; i < x.length; i++) {
      
        var valueString  = x[i].innerHTML.replace(/[$]/g,"");
        counter += parseInt(valueString, 10);
        var j = Math.floor(counter/2.15); 
        x[i].innerHTML += (" " + j +"K");
    }
<div class="item">$25.00</div>

P.S : Do not forget to give counter an initial value 0 if you want to use +=

0
Yamen Nassif On

This will remove all non-digit characters using JQuery:

var str=$(".item").text();
str = parseInt(str.replace(/[^0-9\.]/g, ''));
$("#result").text("results is :"+str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item">$25.00K</div>
<div id="result"></div>

without JQuery :

var x = document.getElementsByClassName("item");
var i;
var counter;
var str= x.textContent || x.innerText;
var onlyInt = parseInt(str.replace(/[^0-9\.]/g, ''));
0
Santhosh S Kashyap On

You can splice the first and last character if u are not sure if u will get chars at first and last then check if those digits are string For splice use this question How to remove the first and the last character of a string