简体   繁体   English

如何处理输入字符串不允许数字或符号的错误

[英]How do I handle an error for an input string to not allow numbers or symbols

I'm going through an exercise and one of the functions is to write code that takes an input containing only strings and returns the first non-repeating character. 我正在进行一个练习,其中一个功能是编写代码,该代码采用仅包含字符串的输入并返回第一个非重复字符。 I've done that already, but i would like to make it smarter by handling any errors that could be a number or symbol. 我已经做到了,但是我想通过处理可能是数字或符号的任何错误来使其更聪明。 I tried all I could but it seems not to work. 我已经尽力了,但是似乎没有用。 It should be purely letters and spaces taken. 它应该纯粹是字母和空格。

Here is what I have so far. 这是我到目前为止所拥有的。

function TheOutput(word){
  var a =word.length;          
  for(var i=0;   i < a;  i++){
  var char=word.charAt(i);
  if(word.indexOf(char)===word.lastIndexOf(char)){
    result = (char + " is not a number <br/>");                
    break;
  }
  return result;
  }
}

You can use regular expressions if you want to test if string is containing only letters and spaces. 如果要测试字符串是否仅包含字母和空格,则可以使用正则表达式。

var onlyLettersAndSpace = 'Valid string';
var stringWithNumbers = 'Invalid string 123';
var RegExpression = new RegExp(/^[a-zA-Z\s]*$/);
console.log(RegExpression.test(onlyLettersAndSpace));
// true
console.log(RegExpression.test(stringWithNumbers));
// false

In your case, you could do something like: 就您而言,您可以执行以下操作:

function testWord(word) {
    var RegExpression = new RegExp(/^[a-zA-Z\s]*$/);
    return RegExpression.test(word);
}

You can do a lot more with regular expressions, see RegExp MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp 您可以使用正则表达式执行更多操作,请参见RegExp MDN: https//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM