Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting string to int in javascript returns NaN

I am trying to convert a phone number on a web page into an integer value but it repeatedly returns NaN, despite being a number. This is part of a chrome extension. My code is as follows:

currNum = String(document.getElementsByClassName("number")[0].innerHTML).trim()
console.log("First: " + currNum)

currNum = currNum.replace("(","").replace(")","").replace("-","").replace(" ","")
console.log("Second: " + currNum)

currNum = parseInt(currNum)
console.log("Third: " + currNum)

The logged output is:

‪First: ‪(206) 000-0000
Second: ‪2060000000
Third: ‪NaN

Is there something about this number that can’t be cast to an int?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks

>Solution :

Use a regex (ie /[()-\s]/g) as the first param of .replace() and instead of " " for a space, use \s which will match all types of whitespace (including the 202A, Pointy mentioned). Also, replace .innerHTML with .textContent

✥ it will match each (, ), -, and whitespace

let currNum = String(document.querySelector(".number").textContent).trim()
console.log("First: " + currNum)

currNum = currNum.replace(/[()-\s]/g,"");
console.log("Second: " + currNum)

currNum = parseInt(currNum)
console.log("Third: " + currNum)
<address>
  <p class='number'>(206) 555-0000</p>
</address>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading