在 JavaScript 中将 string 转换为 int 返回 NaN
我试图将网页上的电话号码转换为整数值,但它反复返回 NaN,尽管它是一个数字。这是 Chrome 扩展的一部分。我的代码如下:
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)
记录的输出是:
First: (206) 000-0000
Second: 2060000000
Third: NaN
这个数字是否有无法转换为 int 的内容?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用正则表达式(即
/[()\s-]/g
)✥ 作为.replace()
的第一个参数,使用\s< 代替
" "
来表示空格/code> 这将匹配所有类型的空白(包括202A,提到的 Pointy)。另外,将
.innerHTML
替换为.textContent
。✥注意:
/[()\ s-]/g
将匹配每个(
,)
、-
和空格。将-
放在表达式末尾,否则可能会被误解为范围。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.