我有一个JavaScript字符串(例如,#box2),我只是想从它的2。
我试着:
var thestring = $(this).attr('href');
var thenum = thestring.replace(/(^.+)(\w\d+\w)(.+$)/i, '$2');
alert(thenum);
它仍然在警告中返回#box2。我怎样才能让它工作呢?
它需要适应任何长度的数字附着在末端。
我有一个JavaScript字符串(例如,#box2),我只是想从它的2。
我试着:
var thestring = $(this).attr('href');
var thenum = thestring.replace(/(^.+)(\w\d+\w)(.+$)/i, '$2');
alert(thenum);
它仍然在警告中返回#box2。我怎样才能让它工作呢?
它需要适应任何长度的数字附着在末端。
当前回答
你可以使用正则表达式从字符串中提取数字:
let string = "xxfdx25y93.34xxd73";
let res = string.replace(/\D/g, "");
console.log(res);
输出:25933473
将它包装成一个普通的JavaScript函数:
function onlyNumbers(text){
return text.replace(/\D/g, "");
}
其他回答
可以使用正则表达式。
var txt="some text 2";
var numb = txt.match(/\d/g);
alert (numb);
那会引起警报。
使用匹配函数。
var thenum = “0a1bbb2”.match(/\d+$/)[0]; console.log(thenum);
函数只是数字(字符串) { var numsStr = string.replace(/[^0-9]/g, ''); 返回 parseInt(numsStr); } console.log(justNumbers('abcdefg12hijklmnop'));
你可以做一个这样的函数
function justNumbers(string)
{
var numsStr = string.replace(/[^0-9]/g, '');
return parseInt(numsStr);
}
记住:如果数字前面有一个0,int就不会有它
对于#box2这样的字符串,这应该是有效的:
var thenum = thestring.replace(/^.*?(\d+).*/,'$1');
jsFiddle:
http://jsfiddle.net/dmeku/
var elValue = "-12,erer3 4,-990.234sdsd";
var isNegetive = false;
if(elValue.indexOf("-") == 0)
isNegetive = true;
elValue = elValue.replace( /[^\d\.]*/g, '');
elValue = isNaN(Number(elValue)) ? 0 : Number(elValue);
if(isNegetive)
elValue = 0 - elValue;
alert(elValue); // -1234990.234