我有一个JavaScript字符串(例如,#box2),我只是想从它的2。

我试着:

var thestring = $(this).attr('href');
var thenum = thestring.replace(/(^.+)(\w\d+\w)(.+$)/i, '$2');
alert(thenum);

它仍然在警告中返回#box2。我怎样才能让它工作呢?

它需要适应任何长度的数字附着在末端。


当前回答

你可以使用parseInt()方法。

它将把前导数字转换为一个数字:

parseInt("-10px");
// Will give you -10

其他回答

使用正则表达式,如何从字符串中获取数字,例如:

String myString = "my 2 first gifts were made by my 4 brothers";
myString = myString.replaceAll("\\D+", "");
System.out.println("myString: " + myString);

myString的结果是“24”。

您可以在http://ideone.com/iOCf5G上看到此运行代码的示例。

我认为这个正则表达式可以满足你的目的:

var num = txt.replace(/[^0-9]/g, '');

txt是你的字符串。

它基本上会扯掉任何不是数字的东西。

我认为你也可以通过使用这个来达到同样的目的:

var num = txt.replace(/\D/g, '');

如果有人需要在提取的数字中保存圆点:

var some = '65,87 EUR';
var number = some.replace(",",".").replace(/[^0-9&.]/g,'');
console.log(number); // returns 65.87

使用匹配函数。

var thenum = “0a1bbb2”.match(/\d+$/)[0]; console.log(thenum);

下面是一个无数据检查的解决方案:

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');
}