Search code examples
javascriptstringcastinginnerhtml

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


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.


    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>