解析Int返回NaN,尽管文本中有数字



嘿,我一直在使用一个转录api,由于某种原因,每次我使用parseInt(语音(时,它都会返回NaN,尽管文本中有一个数字

这是我的代码:

${parseInt(req.body.Speech)}

以下是日志:

SPEECH:
your code is 156 please enter the code now,
CODE:
NaN

我完全不知道它为什么要这么做。据我所知,它应该只是归还156。非常感谢您的帮助。

简单地说,如果parseInt遇到不是数字的东西,它会停在那里,直到遇到任何数字,它都会尝试解析。您的字符串仅以字符串开头。

your code is 156 please enter the code now,

当它在第一个字符上看到y时,它就停止了,因为y不是任何数字系统的一部分(十六进制有af(。因此,在此之前,它解析了一个空字符串""。因此,从技术上讲,parseInt("")NaN或不是一个数字。

所以你可以做任何类似的事情,在字符串中有一个数字和一个字符串:

// Possible
console.log(parseInt("15 kg"));        //  15
console.log(parseInt("120 seconds"));  // 120
// Not Possible
console.log(parseInt("Hello 420"));    // NaN

如果您仍然需要从字符串中查找数字,您可以使用RegEx:

// Possible
console.log(parseInt("15 kg"));        //  15
console.log(parseInt("120 seconds"));  // 120
// Possible with Regex
console.log(parseInt("Hello 420 Folks".replace(/^D+|D+$/g, "")));                              // 420
console.log(parseInt("your code is 156 please enter the code now,".replace(/^D+|D+$/g, "")));  // 156


来自手册:

如果parseInt在指定的radix中遇到一个不是数字的字符,它将忽略该字符和所有后续字符,并返回到该点为止解析的整数值。parseInt将数字截断为整数值。允许使用前导空格和尾随空格。

parseInt仅适用于包含数字的字符串。如果字符串包含字母数字值。它不起作用。您必须从字符串中提取数字,然后转换为数字或解析int。另一件事你可以试试Number("把你的字符串传给这里"(。

我建议,从后端只需在前端的reponse.body.speech.中发送代码,就可以使整个字符串像"您的代码是{request.body.speech}}请立即输入代码";

您可以使用正则表达式。。。

const getNum = s => parseInt(s.replace(/^D+/g,''))
console.log( getNum('your code is 156 please enter the code now') )

如果你只想要数字,试试这样的方法:

let fullSentence = "your code is 156 please enter the code now,";
fullSentence = fullSentence.match(/d/g).join("")
console.log(parseInt(fullSentence));

它检查你的句子是否有数字,并将所有数字放在一起,最后将字符串解析为int。

您需要首先从句子中提取数字,然后将其转换为整数。

const sentence = "your code is 156 please enter the code now,";
const res = sentence.match(/d+/g);
if (res){
console.log(parseInt(res[0], 10));
} else {
console.log("there was no number on the input");
}

如果字符串中有多个数字,并且希望每个数字都有一个数组,则可以使用带有正则表达式的split函数:

'abc123def456'.split(/D/).filter(Boolean) // [123, 456]

.split(/D/)将在非数字字符上进行拆分,删除它们

.filter(Boolean)将删除数组中的空字符串项目

最新更新