在javascript中如何将字符串(';No.10';)转换为数字10和(';18.12';)转换为18.12?
这就是问题所在: 编写一个函数parseFirstInt,该函数接受一个字符串并返回字符串中的第一个整数。如果字符串不包含整数,则应获取NaN。parseFirstInt('No.10')应返回10,parseFirstInt('Babylon')应返回NaN 我使用parseFloat和parseInt,但不解决它 我的代码在这里:在javascript中如何将字符串(';No.10';)转换为数字10和(';18.12';)转换为18.12?,javascript,Javascript,这就是问题所在: 编写一个函数parseFirstInt,该函数接受一个字符串并返回字符串中的第一个整数。如果字符串不包含整数,则应获取NaN。parseFirstInt('No.10')应返回10,parseFirstInt('Babylon')应返回NaN 我使用parseFloat和parseInt,但不解决它 我的代码在这里: parseFirstInt = function(str){ var a = str.replace(/[^0-9]/g, "
parseFirstInt = function(str){
var a = str.replace(/[^0-9]/g, "");
var b = parseFloat(a);
return b;
}
//parseFirstInt('No. 10') return 10
//BUT parseFirstInt('18.12') return 1812
我希望有帮助
function parseFirstInt(str){
const reg = RegExp(/\d+/g);
let arr = reg.exec(str);
if(arr == null){
return NaN;
}
return arr[0];
}
var res = parseFirstInt("India9Delhi78Asia67");
console.log(res); // 9
您可以使用regx/(\d)+/g获取数字。请参阅下面的代码
var str=“第10号”;
警报(编号(str.match(/(\d)+/g)[0]) 您正在剥离所有非数字字符,其中包括“18.12”中的
。请详细说明与“整数”相关的意图。我知道整数是什么,但问题的措辞听起来不像是要处理BigInt、其他数字符号等。更具体地说,例如,“123456789012345678”
,“011”
,“3e14”
,“0x14”
,“-0”
,“18.12”
。。。