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

我试着:

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

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

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


当前回答

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

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

其他回答

您需要添加“(/\d+/g)”,这将删除所有非数字文本,但它仍然是一个字符串。如果您通过匹配创建了一个变量和“parseInt”,您可以将新变量设置为数组值。下面是我如何让它工作的一个例子:

    var color = $( this ).css( "background-color" );
    var r = parseInt(color.match(/\d+/g)[0]);
    var g = parseInt(color.match(/\d+/g)[1]);
    var b = parseInt(color.match(/\d+/g)[2]);

你应该尝试以下方法:

var txt = "#div-name-1234-characteristic:561613213213";
var numb = txt.match(/\d/g);
numb = numb.join("");
alert (numb);​

结果

1234561613213213

可以使用正则表达式。

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

那会引起警报。

你可以使用parseInt()方法。

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

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

对于#box2这样的字符串,这应该是有效的:

var thenum = thestring.replace(/^.*?(\d+).*/,'$1');

jsFiddle:

http://jsfiddle.net/dmeku/