我有一个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。我怎样才能让它工作呢?
它需要适应任何长度的数字附着在末端。
当前回答
请检查下面的JavaScript代码。在那里你只能得到一个数字。
var txt=“abc1234char5678#!9”; var str = txt.match(/\d+/g, “”) + ''; var s = str.split(',').join(''); 警报(数量);
输出:1234567789
其他回答
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
可以使用正则表达式。
var txt="some text 2";
var numb = txt.match(/\d/g);
alert (numb);
那会引起警报。
我认为这个正则表达式可以满足你的目的:
var num = txt.replace(/[^0-9]/g, '');
txt是你的字符串。
它基本上会扯掉任何不是数字的东西。
我认为你也可以通过使用这个来达到同样的目的:
var num = txt.replace(/\D/g, '');
如果你想从价格(如$6,694.20)中解析一个数字,可以这样做:
parseFloat('$6,694.20'.replace(/^\D|,+/g, ''))
或者通过函数:
function parsePrice(value) {
return parseFloat(value.replace(/^\D|,+/g, ''))
}
parsePrice('$6,694.20') // 6694.2
你可以使用parseInt()方法。
它将把前导数字转换为一个数字:
parseInt("-10px");
// Will give you -10