Javascript: Trouble Convertting String to Number
Given the circumstances, I have to use a node list to get the items I need to work with. I can use .textContent
(or .nodeValue
) to return the string that I need, but I am having a hard time finding a way to get that string to any type of number. I need to have it as a number so that I can do calculations with it. I've tried Number()
, parseInt()
etc. Everyone comes back NaN
. I'm new to JS so hopefully this is a tricky task 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 who say this is an invisible character are probably right. I'm trying to make changes to a SharePoint page, so I'm not familiar with markup. Any suggestions on how to remove everything but the number would be helpful.
source to share
Your code should work as it is if the content is really simple 1
(like parseInt
). Thus, there must be something other than valid in your content.
Sometimes there may be content that you don't see, for example. in the example below, the second td
contains an invisible zero-width 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>​2</td>
</tr></table>
You can remove all non-digit characters (except .
and ,
) with a regular expression like:
siteActual = siteActual.replace(/[^\d.,]/g, '');
source to share
Using parseInt(...)
Example:
var siteActual = tdNodeListActual[36].textContent; // location of data
console.log(siteActual); // returns the value 1 as it should
var asd = Number(parseInt(siteActual)); // test variable to convert string to number
console.log(asd); // should return 1
source to share