我有一个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。我怎样才能让它工作呢?
它需要适应任何长度的数字附着在末端。
当前回答
如果你想从价格(如$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 price = "£1,739.12";
parseFloat(price.replace(/[^\d\.]*/g, '')); // 1739.12
Use:
changeStrangeDate(dateString: string) {
var sum = 0;
var numbers = dateString.match(/\d+/g);
if (numbers.length > 1) {
numbers.forEach(element => {
sum += parseInt(element);
}
);
}
console.log(new Date(sum).toDateString());
return new Date(sum).toUTCString();
}
你可以这样做,然后在需要的地方用一个参数调用一个函数。
this.changeStrangeDate('/Date(1551401820000-0100)/');
你应该尝试以下方法:
var txt = "#div-name-1234-characteristic:561613213213";
var numb = txt.match(/\d/g);
numb = numb.join("");
alert (numb);
结果
1234561613213213
这个答案将涵盖大多数场景。当一个用户试图复制粘贴电话号码时,我遇到了这种情况。
$('#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'))
});
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