Extract a number from a string (JavaScript)

前端 未结 22 1427
灰色年华
灰色年华 2020-11-22 06:38

I have a string in JavaScript like #box2 and I just want the 2 from it.

I tried:

var thestring = $(this).attr(\'href\');
var          


        
22条回答
  •  失恋的感觉
    2020-11-22 07:06

    For this specific example,

     var thenum = thestring.replace( /^\D+/g, ''); // replace all leading non-digits with nothing
    

    in the general case:

     thenum = "foo3bar5".match(/\d+/)[0] // "3"
    

    Since this answer gained popularity for some reason, here's a bonus: regex generator.

    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: ' + re + '';
    }

    Hi, I'm Numex, the Number Extractor Oracle.

    What is your string?

    What number do you want to extract?

提交回复
热议问题