我有一个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
其他回答
这个答案将涵盖大多数场景。当一个用户试图复制粘贴电话号码时,我遇到了这种情况。
$('#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 thenum = thestring.replace(/^\D+/g, ''); // Replace all leading non-digits with nothing
一般情况下:
thenum = "foo3bar5".match(/\d+/)[0] // "3"
这里有一个奖励:正则表达式生成器。
function getre(str, num) { if(str === num) return 'nice try'; var res = [/^\D+/g,/\D+$/g,/^\D+|\D+$/g,/\D+/g,/\D.*/g, /.*\D/g,/^\D+|\D.*$/g,/.*\D(?=\d)|\D+$/g]; for(var i = 0; i < res.length; i++) if(str.replace(res[i], '') === num) return 'num = str.replace(/' + res[i].source + '/g, "")'; return 'no idea'; }; function update() { $ = function(x) { return document.getElementById(x) }; var re = getre($('str').value, $('num').value); $('re').innerHTML = 'Numex speaks: <code>' + re + '</code>'; } <p>Hi, I'm Numex, the Number Extractor Oracle. <p>What is your string? <input id="str" value="42abc"></p> <p>What number do you want to extract? <input id="num" value="42"></p> <p><button onclick="update()">Insert Coin</button></p> <p id="re"></p>
您需要添加“(/\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]);
可以使用正则表达式。
var txt="some text 2";
var numb = txt.match(/\d/g);
alert (numb);
那会引起警报。
我认为这个正则表达式可以满足你的目的:
var num = txt.replace(/[^0-9]/g, '');
txt是你的字符串。
它基本上会扯掉任何不是数字的东西。
我认为你也可以通过使用这个来达到同样的目的:
var num = txt.replace(/\D/g, '');