在 javascript returns NaN 中将字符串转换为 int
Converting string to int in javascript returns NaN
我正在尝试将网页上的 phone 数字转换为整数值,但它重复 returns 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 的吗?
谢谢
使用正则表达式(即 /[()\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)。另外,将 .innerHTML
替换为 .textContent
.
✥注: /[()\s-]/g
会匹配每个 (
, )
, -
和空格。将 -
放在表达式的末尾,否则它可能会被误解为一个范围。
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>
currNum = currNum.replace(/[\s()-]/g, '')
我正在尝试将网页上的 phone 数字转换为整数值,但它重复 returns 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 的吗?
谢谢
使用正则表达式(即 /[()\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)。另外,将 .innerHTML
替换为 .textContent
.
✥注: /[()\s-]/g
会匹配每个 (
, )
, -
和空格。将 -
放在表达式的末尾,否则它可能会被误解为一个范围。
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>
currNum = currNum.replace(/[\s()-]/g, '')