如何检查字符串中是否包含字母或字符?

时间:2019-06-26 08:11:29

标签: javascript string input

我需要检查输入是否只有数字和空格(没有字母或字符)。

尝试使用.includes


var string = 'abc'

if(string.includes(A-Za)){
console.log('bad')
} else {
console.log('good')
}

5 个答案:

答案 0 :(得分:2)

使用Regex.test()

//what i want
string limited="hello world";
//error;
string limited="update";
//not error;
string any_other_string_name_exept_limited="hello world";
//not error;
string any_other_string_name_exept_limited="update";
//not error;

答案 1 :(得分:1)

只需使用一个简单的正则表达式来匹配数字从头到尾:

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));

答案 2 :(得分:1)

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";
}

崩溃:^(\d|\s)*$

  • ^:字符串的开头
  • $:字符串结尾
  • \d:匹配数字(也可以写为[0-9]
  • \s:匹配一个空格或任何其他空格字符(如果只需要空格,则
  • \d|\s:匹配号码或空格
  • (\d|\s)*:匹配数字或空格0次-多次(也可以写为(\d|\s){0,}

答案 3 :(得分:0)

尝试使用此正则表达式 ^ [0-9] * $

console.log( /^[0-9]*$/.test('45') ? "Good" : "Bad")

enter image description here

答案 4 :(得分:0)

检查每个字符:

for (i = 0; i < string.length; i++) { 
  if (isNan(string[i]) && string[i] == ' ') {
  console.log('bad')
} else {
  console.log('good')
}
}
相关问题