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

我试着:

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

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

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


当前回答

在我的一个项目中,我必须从字符串中获取一个评级值。这是我使用的:

let text = '#xbox2'
let num = text.trim().
  split('').
  map(num => Number(num)).
  filter(x => Number.isInteger(x))

其他回答

可以使用正则表达式。

var txt="some text 2";
var numb = txt.match(/\d/g);
alert (numb);

那会引起警报。

使用这一行代码获得字符串中的第一个数字而不会出错:

var myInt = parseInt(myString.replace(/^[^0-9]+/, ''), 10);

我尝试了前一个答案中引用的所有组合与此代码,并得到了它的工作。→(12)3456-7890

var str = "(12) 3456-7890";
str.replace(/\D+/g, '');

结果:“1234567890”

注意事项:我知道这样的字符串不会在属性上,但无论如何,解决方案是更好的,因为它更完整。

你可以使用正则表达式从字符串中提取数字:

let string = "xxfdx25y93.34xxd73";
let res = string.replace(/\D/g, "");
console.log(res);

输出:25933473

将它包装成一个普通的JavaScript函数:

function onlyNumbers(text){
    return text.replace(/\D/g, "");
}

使用匹配函数。

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