检查字符串是否全是数字 [英] Checking whether a string is all digits
问题描述
我正在尝试检查字符串是否都是数字。这部分是
轻松:
函数allDigits(str){
var foo = str.split('''' ); //比charAt更好()?
for(var idx = 0; idx< foo.length; idx ++){
if(!isDigit(foo [idx] )){
返回false;
}
}
返回true;
}
我不确定如何实现isDigit()。这是最好的方式吗?
函数isDigit(s){
if(s.length> 1){
返回false;
}
var nums =''1234567890'';
return nums.indexOf(s)!= -1; < br $>
}
-
Christopher Benson-Manica |我*应该*知道我在说什么 - 如果我
ataru(at)cyberspace.org |不,我需要知道。火焰欢迎。
String.prototype.isdigits = function(){
return(/ \D /。 test(this)== false);
}
如果字符串中没有非数字,则返回true。
因为它是一个原型方法,所以调用它为这样的字符串str:
if(str.isdigits()){做某事}
别的{做别的事情}
Christopher Benson-Manica< at *** @ nospam.cyberspace.org>写道:
我正在尝试检查一个字符串是否都是数字。
为此,正则表达式是最简单的方法,通过一些订单
的大小:)
函数allDigits(str){
返回/ ^ \ 。d *
/测试(STR); //仅包含从头到尾的数字
}
甚至:
函数allDigits(str ){
return!/\D/.test( str); //不包含非数字
}
这接受空字符串,从技术上讲,这是所有数字
(除了数字之外什么都没有)。如果你只想要非空字符串,
将其更改为:
函数allDigits(str){
return / ^ \d +
I''m trying to check whether a string is all digits. This part is
easy:
function allDigits( str ) {
var foo=str.split( '''' ); // better than charAt()?
for( var idx=0; idx < foo.length; idx++ ) {
if( !isDigit(foo[idx]) ) {
return false;
}
}
return true;
}
I''m not sure about how to implement isDigit(). Is this the best way?
function isDigit( s ) {
if( s.length > 1 ) {
return false;
}
var nums=''1234567890'';
return nums.indexOf(s) != -1;
}
--
Christopher Benson-Manica | I *should* know what I''m talking about - if I
ataru(at)cyberspace.org | don''t, I need to know. Flames welcome.
String.prototype.isdigits=function(){
return (/\D/.test(this)==false);
}
This returns true if there are no non-digits in the string.
Since it is a prototype method, call it for a string str like this:
if(str.isdigits()){do something}
else {do something else}
Christopher Benson-Manica <at***@nospam.cyberspace.org> writes:
I''m trying to check whether a string is all digits.
For that, regular expressions is the simplest way, by some orders
of magnitude :)
function allDigits(str) {
return /^\d*
/.test(str); // consists of only digits from start to end
}
or even:
function allDigits(str) {
return !/\D/.test(str); // doesn''t contain non-digit
}
This accepts the empty string, which is, technically, all digits
(there is nothing but digits). If you want only non-empty strings,
change it to:
function allDigits(str) {
return /^\d+
这篇关于检查字符串是否全是数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!