Extract a number from a string (JavaScript)

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

    For a string such as #box2, this should work:

    var thenum = thestring.replace(/^.*?(\d+).*/,'$1');
    

    jsFiddle:

    • http://jsfiddle.net/dmeku/
    0 讨论(0)
  • 2020-11-22 07:20

    please check below javaScripts, there you can get only number

    var txt = "abc1234char5678#!9";
    var str = txt.match(/\d+/g, "")+'';
    var s = str.split(',').join('');
    alert(Number(s));

    output : 1234567789

    0 讨论(0)
  • 2020-11-22 07:20
    changeStrangeDate(dateString: string) {
    var sum = 0;
    var numbers = dateString.match(/\d+/g);
    if (numbers.length > 1) {
      numbers.forEach(element => {
        sum += parseInt(element);
      }
      );
    }
    console.log(new Date(sum).toDateString());
    return new Date(sum).toUTCString();
    

    }

    You can do it like that and then call function where you need, with parameter.

    this.changeStrangeDate('/Date(1551401820000-0100)/');
    
    0 讨论(0)
  • 2020-11-22 07:21

    This answer will cover most of the scenario. I can across this situation when user try to copy paste the phone number

      $('#help_number').keyup(function(){
        $(this).val().match(/\d+/g).join("")
      });
    

    Explanation:

    str= "34%^gd 5-67 6-6ds"
    
    str.match(/\d+/g)
    

    It will give a array of string as output >> ["34", "56766"]

    str.match(/\d+/g).join("")
    

    join will convert and concatenate that array data into single string

    output >> "3456766"

    In my example I need the output as 209-356-6788 so I used replace

      $('#help_number').keyup(function(){
        $(this).val($(this).val().match(/\d+/g).join("").replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
      });
    
    0 讨论(0)
提交回复
热议问题