从字符串中提取数字(JavaScript)

用户名

我在JavaScript中有一个类似的字符串,#box2我只想要2它。

我试过了:

var thestring = $(this).attr('href');
var thenum = thestring.replace( /(^.+)(\w\d+\w)(.+$)/i,'$2');
alert(thenum);

它仍然会#box2在警报中返回,如何使它正常工作?

它需要容纳末尾附加的任何长度的数字。

乔治

对于此特定示例,

 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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章