我有一个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。我怎样才能让它工作呢?
它需要适应任何长度的数字附着在末端。
当前回答
要从字符串返回int,可以执行以下代码。它删除所有非数字字符并返回一个整数。
Number("strin[g]3".replace(/\D+/g, ""))
其他回答
在我的一个项目中,我必须从字符串中获取一个评级值。这是我使用的:
let text = '#xbox2'
let num = text.trim().
split('').
map(num => Number(num)).
filter(x => Number.isInteger(x))
使用匹配函数。
var thenum = “0a1bbb2”.match(/\d+$/)[0]; console.log(thenum);
我尝试了前一个答案中引用的所有组合与此代码,并得到了它的工作。→(12)3456-7890
var str = "(12) 3456-7890";
str.replace(/\D+/g, '');
结果:“1234567890”
注意事项:我知道这样的字符串不会在属性上,但无论如何,解决方案是更好的,因为它更完整。
你可以使用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上看到此运行代码的示例。