怎样才能使用jquery从文本中获取数字

时间:2011-12-02 13:35:42

标签: javascript jquery

我想只得到数字(123)而不是文本(确认),这是我的代码

<p>123confirm</p>

<script type="text/javascript">
$(document).ready(function(){  
  $('p').click(function(){  
    var sd=$(this).text();  
    alert(sd);
  });
});  
</script>

4 个答案:

答案 0 :(得分:36)

我认为RegExp是个好主意:

var sd = $(this).text().replace(/[^0-9]/gi, ''); // Replace everything that is not a number with nothing
var number = parseInt(sd, 10); // Always hand in the correct base since 010 != 10 in js

答案 1 :(得分:22)

你可以使用parseInt,它将解析一个字符串并删除任何&#34;垃圾&#34;在其中并返回一个整数。

James Allardice注意到,这个数字必须在字符串之前。因此,如果它是文本中的第一件事,它将起作用,否则它就不会。

- 编辑 - 与您的示例一起使用:

<p>123confirm</p>

<script type="text/javascript">
$(document).ready(function(){  
  $('p').click(function(){  
    var sd=$(this).text();  
    sd=parseInt(sd);
    alert(sd);
  });
});  
</script>

答案 2 :(得分:4)

您也可以使用此方法:

$(document).ready(function(){  
  $(p).click(function(){  
    var sd=$(this).text();
    var num = sd.match(/[\d\.]+/g);
    if (num != null){
        var number = num.toString();
        alert(number );
    }
  });
});  

答案 3 :(得分:1)

您也可以使用此方法:

 $('#totalseat').change(function() {
    var totalseat=$('#totalseat').val();
    var price=$('#seat_type option:selected').text().replace(/[^0-9]/gi,'');
    // Always hand in the correct base since 010 != 10 in js
    var price_int = parseInt(price,10);
    var total_price=parseInt(totalseat)*price_int;
    $('#totalprice').val(total_price);

});