Extract a number from a string (JavaScript)

前端 未结 22 1378
灰色年华
灰色年华 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:13

    Tried all the combinations cited above with this Code and got it working, was the only one that worked on that string -> (12) 3456-7890

    var str="(12) 3456-7890";
    str.replace( /\D+/g, '');
    

    Result: "1234567890"

    Obs: i know that a string like that will not be on the attr but whatever, the solution is better, because its more complete.

    0 讨论(0)
  • 2020-11-22 07:13

    you may use great parseInt method

    it will convert the leading digits to a number

    parseInt("-10px");
    // will give you -10
    
    0 讨论(0)
  • 2020-11-22 07:14

    I think this regular expression will serve your purpose:

    var num = txt.replace(/[^0-9]/g,'');
    

    Where txt is your string.

    It basically rips off anything that is not a digit.

    I think you can achieve the same thing by using this as well :

    var num = txt.replace(/\D/g,'');
    
    0 讨论(0)
  • 2020-11-22 07:14

    Using match function.

    var thenum = thestring.match(/\d+$/)[0];
    alert(thenum);
    

    jsfiddle

    0 讨论(0)
  • 2020-11-22 07:16

    And this is a snippet which extracts prices with currency and formatting:

    var price = "£1,739.12";
    parseFloat(price.replace( /[^\d\.]*/g, '')); // 1739.12
    
    0 讨论(0)
  • 2020-11-22 07:18

    Use this one-line code to get the first number in a string without getting errors:

    var myInt = parseInt(myString.replace(/^[^0-9]+/, ''), 10);
    
    0 讨论(0)
提交回复
热议问题