我有一个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。我怎样才能让它工作呢?
它需要适应任何长度的数字附着在末端。
当前回答
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)
其他回答
使用匹配函数。
var thenum = “0a1bbb2”.match(/\d+$/)[0]; console.log(thenum);
请检查下面的JavaScript代码。在那里你只能得到一个数字。
var txt=“abc1234char5678#!9”; var str = txt.match(/\d+/g, “”) + ''; var s = str.split(',').join(''); 警报(数量);
输出:1234567789
使用这一行代码获得字符串中的第一个数字而不会出错:
var myInt = parseInt(myString.replace(/^[^0-9]+/, ''), 10);
我认为这个正则表达式可以满足你的目的:
var num = txt.replace(/[^0-9]/g, '');
txt是你的字符串。
它基本上会扯掉任何不是数字的东西。
我认为你也可以通过使用这个来达到同样的目的:
var num = txt.replace(/\D/g, '');
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)/');