我有一个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”
注意事项:我知道这样的字符串不会在属性上,但无论如何,解决方案是更好的,因为它更完整。
其他回答
请检查下面的JavaScript代码。在那里你只能得到一个数字。
var txt=“abc1234char5678#!9”; var str = txt.match(/\d+/g, “”) + ''; var s = str.split(',').join(''); 警报(数量);
输出:1234567789
可以使用正则表达式。
var txt="some text 2";
var numb = txt.match(/\d/g);
alert (numb);
那会引起警报。
对于这个具体的例子,
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>
对于#box2这样的字符串,这应该是有效的:
var thenum = thestring.replace(/^.*?(\d+).*/,'$1');
jsFiddle:
http://jsfiddle.net/dmeku/
我尝试了前一个答案中引用的所有组合与此代码,并得到了它的工作。→(12)3456-7890
var str = "(12) 3456-7890";
str.replace(/\D+/g, '');
结果:“1234567890”
注意事项:我知道这样的字符串不会在属性上,但无论如何,解决方案是更好的,因为它更完整。