Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

245
Views
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?

Thanks

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.


✥Note: /[()\s-]/g will match each (, ), -, and whitespace. Place the - at the end of expression or it could be misinterpreted as a range.

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>

about 4 years ago · Juan Pablo Isaza Report

0

currNum = currNum.replace(/[\s()-]/g, '')
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!