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

我试着:

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

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

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


当前回答

试试下面的:string。替换(/ [^ 0 - 9]/ g,”);这将删除所有非数字字符,在字符串中只留下数字

function retnum(str) { 
    var num = str.replace(/[^0-9]/g, ''); 
    return parseInt(num,10); 
}

console.log(“abca12bc45qw”。替换(/ [^ 0 - 9]/ g, ")); console.log(“# box2”。替换(/ [^ 0 - 9]/ g, "));

其他回答

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

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

对于这个具体的例子,

 var thenum = thestring.replace(/^\D+/g, ''); // Replace all leading non-digits with nothing

一般情况下:

 thenum = "foo3bar5".match(/\d+/)[0] // "3"

这里有一个奖励:正则表达式生成器。

function getre(str, num) { if(str === num) return 'nice try'; var res = [/^\D+/g,/\D+$/g,/^\D+|\D+$/g,/\D+/g,/\D.*/g, /.*\D/g,/^\D+|\D.*$/g,/.*\D(?=\d)|\D+$/g]; for(var i = 0; i < res.length; i++) if(str.replace(res[i], '') === num) return 'num = str.replace(/' + res[i].source + '/g, "")'; return 'no idea'; }; function update() { $ = function(x) { return document.getElementById(x) }; var re = getre($('str').value, $('num').value); $('re').innerHTML = 'Numex speaks: <code>' + re + '</code>'; } <p>Hi, I'm Numex, the Number Extractor Oracle. <p>What is your string? <input id="str" value="42abc"></p> <p>What number do you want to extract? <input id="num" value="42"></p> <p><button onclick="update()">Insert Coin</button></p> <p id="re"></p>

var elValue = "-12,erer3  4,-990.234sdsd";

var isNegetive = false;
if(elValue.indexOf("-") == 0)
    isNegetive = true;

elValue = elValue.replace( /[^\d\.]*/g, '');
elValue = isNaN(Number(elValue)) ? 0 : Number(elValue);

if(isNegetive)
    elValue = 0 - elValue;

alert(elValue); // -1234990.234

如果你想从价格(如$6,694.20)中解析一个数字,可以这样做:

parseFloat('$6,694.20'.replace(/^\D|,+/g, ''))

或者通过函数:

function parsePrice(value) {
  return parseFloat(value.replace(/^\D|,+/g, ''))
}

parsePrice('$6,694.20') // 6694.2

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

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