我有一个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。我怎样才能让它工作呢?
它需要适应任何长度的数字附着在末端。
当前回答
下面是一个无数据检查的解决方案:
var someStr = 'abc'; // Add 123 to string to see the inverse
var thenum = someStr.match(/\d+/);
if (thenum != null)
{
console.log(thenum[0]);
}
else
{
console.log('Not a number');
}
其他回答
我尝试了前一个答案中引用的所有组合与此代码,并得到了它的工作。→(12)3456-7890
var str = "(12) 3456-7890";
str.replace(/\D+/g, '');
结果:“1234567890”
注意事项:我知道这样的字符串不会在属性上,但无论如何,解决方案是更好的,因为它更完整。
使用匹配函数。
var thenum = “0a1bbb2”.match(/\d+$/)[0]; console.log(thenum);
可以使用正则表达式。
var txt="some text 2";
var numb = txt.match(/\d/g);
alert (numb);
那会引起警报。
这是一个用货币和格式提取价格的代码片段:
var price = "£1,739.12";
parseFloat(price.replace(/[^\d\.]*/g, '')); // 1739.12
如果你想从价格(如$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