Javascript 如何使用 jquery 从文本中只获取数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8357138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how can get only numbers from the text using jquery
提问by Suresh Pattu
I want to get only the numbers(123) not the text(confirm), here is my code
我只想得到数字(123)而不是文本(确认),这是我的代码
<p>123confirm</p>
<script type="text/javascript">
$(document).ready(function(){
$('p').click(function(){
var sd=$(this).text();
alert(sd);
});
});
</script>
回答by mfeineis
I think a RegExp would be a good idea:
我认为 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
回答by jValdron
You can use parseInt
for this, it will parse a string and remove any "junk" in it and return an integer.
您可以使用parseInt
它,它将解析一个字符串并删除其中的任何“垃圾”并返回一个整数。
As James Allardice noticed, the number must be before the string. So if it's the first thing in the text, it will work, else it won't.
正如 James Allardice 所注意到的,数字必须在字符串之前。所以如果它是文本中的第一件事,它会起作用,否则它不会。
-- EDIT -- Use with your example:
-- 编辑 -- 与您的示例一起使用:
<p>123confirm</p>
<script type="text/javascript">
$(document).ready(function(){
$('p').click(function(){
var sd=$(this).text();
sd=parseInt(sd);
alert(sd);
});
});
</script>
回答by Sal
You can also use this method:
你也可以使用这个方法:
$(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 );
}
});
});
回答by Sani Kamal
You can also use this method:
你也可以使用这个方法:
$('#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);
});