我有一个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 num = txt.replace(/[^0-9]/g, '');

txt是你的字符串。

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

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

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

这是一个用货币和格式提取价格的代码片段:

var price = "£1,739.12";
parseFloat(price.replace(/[^\d\.]*/g, '')); // 1739.12

你可以使用parseInt()方法。

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

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

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

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

函数只是数字(字符串) { 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就不会有它