Check if string contains only digits

六眼飞鱼酱① 提交于 2019-11-26 17:05:29

how about

var isnum = /^\d+$/.test(val);
string.match(/^[0-9]+$/) != null;
String.prototype.isNumber = function(){return /^\d+$/.test(this);}
console.log("123123".isNumber()); // outputs true
console.log("+12".isNumber()); // outputs false

If you want to even support for float values (Dot separated values) then you can use this expression :

var isNumber = /^\d+\.\d+$/.test(value);

This is what you want

function isANumber(str){
  return !/\D/.test(str);
}

Here's another interesting, readable way to check if a string contains only digits.

This method works by splitting the string into an array using the spread operator, and then uses the every() method to test whether all elements (characters) in the array are included in the string of digits '0123456789':

const digits_only = string => [...string].every(c => '0123456789'.includes(c));

console.log(digits_only('123')); // true
console.log(digits_only('+123')); // false
console.log(digits_only('-123')); // false
console.log(digits_only('123.')); // false
console.log(digits_only('.123')); // false
console.log(digits_only('123.0')); // false
console.log(digits_only('0.123')); // false
console.log(digits_only('Hello, world!')); // false

Well, you can use the following regex:

^\d+$

Here is a solution without using regular expressions:

function onlyDigits(s) {
  for (let i = s.length - 1; i >= 0; i--) {
    const d = s.charCodeAt(i);
    if (d < 48 || d > 57) return false
  }
  return true
}

where 48 and 57 are the char codes for "0" and "9", respectively.

Peter Hollingsworth
function isNumeric(x) {
    return parseFloat(x).toString() === x.toString();
}

Though this will return false on strings with leading or trailing zeroes.

c="123".match(/\D/) == null #true
c="a12".match(/\D/) == null #false

If a string contains only digits it will return null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!