Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Trouble Converting String to Number

Tags:

javascript

Given the circumstances I have to use a node list to get at elements that I need to work with. I am able to use .textContent (or .nodeValue) to return a string that I need, but I am having trouble finding a way to get that string into any type of number. I need to have it in number form so I can perform calculations with it. I have tried Number(), parseInt(), etc. All return NaN. I am pretty new to JS so hopefully this is an easy issue to solve.

var siteActual = tdNodeListActual[36].textContent; // location of data
console.log(siteActual); // returns the value 1 as it should

var asd = Number(siteActual); // test variable to convert string to number
console.log(asd); // returns NaN

EDIT: I checked .length as one of you suggested and it was 2, so those saying it may be an invisible character are probably right. I am trying to make changes to a SharePoint page, that is why I am not familiar with what the markup is. Any suggestions on how to remove all but the number would be helpful.

like image 351
robbieyng Avatar asked Feb 10 '26 06:02

robbieyng


1 Answers

Your code should work as-is if the content is really just 1 (as should parseInt). So there must be something other than valid numbers in your content.

Sometimes there can be content that you can't see, e.g. in the example below the second td contains an invisible "zero-width space" character.

var tdNodeListActual = document.querySelectorAll("td");

var good = tdNodeListActual[0].textContent;
var bad = tdNodeListActual[1].textContent;

alert(good + "==" + Number(good) + ", but " + bad + "==" + Number(bad))
<table><tr>
  <td>1</td>
  <td>&#8203;2</td>
</tr></table>

You can remove all non-digit characters (except . and ,) using a regex, e.g.:

siteActual = siteActual.replace(/[^\d.,]/g, '');
like image 199
CupawnTae Avatar answered Feb 13 '26 03:02

CupawnTae



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!