I need to check if input has only numbers and spaces(no letters or characters).
Tried using .includes
var string = 'abc'
if(string.includes(A-Za)){
console.log('bad')
} else {
console.log('good')
}
I need to check if input has only numbers and spaces(no letters or characters).
Tried using .includes
var string = 'abc'
if(string.includes(A-Za)){
console.log('bad')
} else {
console.log('good')
}
Using Regex.test()
var string = 'abc'
if (/[A-Za-z]/.test(string)) {
console.log('bad')
} else {
console.log('good')
}
Just use a simple regex that matches numbers from start to end:
const bad = 'abc';
const good = 123;
const re = /^\d*$/;
const goodOrBad = str => re.test(str) ? "Good" : "Bad";
console.log(goodOrBad(bad));
console.log(goodOrBad(good));
console.log(check("abc"));
console.log(check("123"));
console.log(check("123 123"));
console.log(check("123 abc"));
function check(txt) {
return /^(\d|\s)*$/.test(txt) ? "good" : "bad";
}
Breakdown of: ^(\d|\s)*$
^
: Start of string$
: End of string\d
: Match a number (Can also be written as [0-9]
)\s
: Match a space or any other whitespace character (if you just want space then
)\d|\s
: Match number or space(\d|\s)*
: Match number or space 0-Many times (Can also be written as (\d|\s){0,}
)checking every character:
for (i = 0; i < string.length; i++) {
if (isNan(string[i]) && string[i] == ' ') {
console.log('bad')
} else {
console.log('good')
}
}