我有一个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。我怎样才能让它工作呢?
它需要适应任何长度的数字附着在末端。
当前回答
这是一个用货币和格式提取价格的代码片段:
var price = "£1,739.12";
parseFloat(price.replace(/[^\d\.]*/g, '')); // 1739.12
其他回答
无正则表达式的:
没有正则表达式 函数提取数字(字符串) { let numArray = string.split('').map(item => { if (typeof +item === 'number' && !isNaN(+item)) 退货 +商品 }) return +numArray.join('') } 提取数字('@1200milion$') // 1200
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 txt = "#div-name-1234-characteristic:561613213213";
var numb = txt.match(/\d/g);
numb = numb.join("");
alert (numb);
结果
1234561613213213
要从字符串返回int,可以执行以下代码。它删除所有非数字字符并返回一个整数。
Number("strin[g]3".replace(/\D+/g, ""))
函数只是数字(字符串) { var numsStr = string.replace(/[^0-9]/g, ''); 返回 parseInt(numsStr); } console.log(justNumbers('abcdefg12hijklmnop'));
你可以做一个这样的函数
function justNumbers(string)
{
var numsStr = string.replace(/[^0-9]/g, '');
return parseInt(numsStr);
}
记住:如果数字前面有一个0,int就不会有它