Home > other >  Is there an effective way to see if a string is question?
Is there an effective way to see if a string is question?

Time:01-15

Is it possible to see if a statement is a question, and even better, a question of substance? What I have is very simple but obviously extremely ineffective if statement:

if (string.endsWith("?")) { // }

A question of substance is something that is an actual question, not something stupid like asdfasdfsafas?

CodePudding user response:

An elegant alternative, is the String.prototype.slice method.

Just by:

str.slice(-1);

A negative start index slices the string from length index, to length, being index -1, the last character is extracted:
You could do:

string.slice(-1) == '?'

But as for checking if the question is of substance, I guess Machine Learning comes to play here

CodePudding user response:

var question = "How are you ?"

function isQuestion(input_str) {
    var firstChar = input_str[0];
    var lastChar = input_str[input_str.length - 1];
    return /[A-Z]/.test(firstChar) && lastChar == "?"
}

if (isQuestion(question)) {
     // true
} else {
   // False
}
  •  Tags:  
  • Related