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

我试着:

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

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

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


当前回答

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

其他回答

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

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

输出:25933473

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

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

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

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

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

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

jsFiddle:

http://jsfiddle.net/dmeku/

您需要添加“(/\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]);

这个答案将涵盖大多数场景。当一个用户试图复制粘贴电话号码时,我遇到了这种情况。

$('#help_number').keyup(function() {
  $(this).val().match(/\d+/g).join("")
});

解释:

str = "34%^gd 5-67 6-6ds"

str.match(/\d+/g)

它将给出一个字符串数组作为输出:

["34", "56766"]

 

str.match(/\d+/g).join("")

Join()将转换该数组数据并将其连接为单个字符串。

输出:

"3456766"

在我的例子中,我需要输出为209-356-6788,所以我使用replace():

$('#help_number').keyup(function() {
  $(this).val($(this).val().match(/\d+/g).join("").replace(/(\d{3})\-?(\d{3})\-?(\d{4})/, '$1-$2-$3'))
});