Extract a number from a string (JavaScript)

前端 未结 22 1397
灰色年华
灰色年华 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: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'))
      });
    

提交回复
热议问题