2

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

4
  • 4
    There's a special non-visible character at the start of the currNum value. It's probably there in your source HTML content also; in fact that's the only place it could have come from. Commented Mar 2, 2022 at 2:38
  • Specifically it's character 202A, the "left-to-right embedding" character. That will cause parseInt() to fail. Commented Mar 2, 2022 at 2:38
  • To your .replace() chain you can add .replace(/[^ -~]/g, "") to get rid of it Commented Mar 2, 2022 at 2:46
  • There's a ✥Note added about the placement of the hyphen in the regex. It's just a precaution. Commented Mar 2, 2022 at 3:03

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

4 Comments

Well the plain space (" ") is character 32 (decimal; 0x20) in the basic Latin page, so [^ -~] will reliably strip out any character codes that don't fall into the basic page visible (non-"control") character range.
However of course the code you have will also work.
oh I see you're knocking them out with one replace, carry on then.
Never occured to me to use the literal space as a class, clever.
-1
currNum = currNum.replace(/[\s()-]/g, '')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.