我有一个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。我怎样才能让它工作呢?
它需要适应任何长度的数字附着在末端。
当前回答
使用正则表达式,如何从字符串中获取数字,例如:
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上看到此运行代码的示例。
其他回答
你可以像下面这样使用Underscore.js的字符串库:
var common = "#box"
var href = "#box1"
_(href).strRight(common)
结果将是:1
看:Underscore.string
演示:
http://jsfiddle.net/abdennour/Vyqtt/
HTML代码:
<p>
<a href="#box1" >img1</a>
<a href="#box2" >img2</a>
<a href="#box3" >img3</a>
<a href="#box4" >img4</a>
</p>
<div style="font-size:30px"></div>
JavaScript代码:
var comm = "#box"
$('a').click(function() {
$('div').html(_($(this).attr('href')).strRight(comm))})
如果你有如下后缀:
href="box1az"
您可以使用以下演示:
http://jsfiddle.net/abdennour/Vyqtt/1/
function retrieveNumber(all, prefix, suffix) {
var left = _(all).strRight(prefix);
return _(left).strLeft(suffix);
}
下面是一个无数据检查的解决方案:
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');
}
要从字符串返回int,可以执行以下代码。它删除所有非数字字符并返回一个整数。
Number("strin[g]3".replace(/\D+/g, ""))
let str = "Total Work Duration: 189.56 Hrs.Present: 23.5 Absent: 2";
/* The provided regex globally matches the character
"." and a digit from the string */
let numArr = str.match(/[\d\.]+/g)
/* It returns an array [189.56, ., 23.5, 2], and
uses the filter function to remove the '.' */
numArr = numArr.filter(n => n != '.')
console.log(numArr)
使用正则表达式,如何从字符串中获取数字,例如:
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上看到此运行代码的示例。