我有一个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。我怎样才能让它工作呢?
它需要适应任何长度的数字附着在末端。
当前回答
我尝试了前一个答案中引用的所有组合与此代码,并得到了它的工作。→(12)3456-7890
var str = "(12) 3456-7890";
str.replace(/\D+/g, '');
结果:“1234567890”
注意事项:我知道这样的字符串不会在属性上,但无论如何,解决方案是更好的,因为它更完整。
其他回答
我尝试了前一个答案中引用的所有组合与此代码,并得到了它的工作。→(12)3456-7890
var str = "(12) 3456-7890";
str.replace(/\D+/g, '');
结果:“1234567890”
注意事项:我知道这样的字符串不会在属性上,但无论如何,解决方案是更好的,因为它更完整。
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 some = '65,87 EUR';
var number = some.replace(",",".").replace(/[^0-9&.]/g,'');
console.log(number); // returns 65.87
无正则表达式的:
没有正则表达式 函数提取数字(字符串) { let numArray = string.split('').map(item => { if (typeof +item === 'number' && !isNaN(+item)) 退货 +商品 }) return +numArray.join('') } 提取数字('@1200milion$') // 1200
如果你想从价格(如$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