-3

How can check the entered input is a valid question format using jquery ?

for eg: i have a string "How are you ?" . and i need to identify whether it is a

question or not .Do that all i need is to check whether the string ends with '?' ?. Thanks .

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
KTM
  • 858
  • 4
  • 21
  • 43

3 Answers3

14

This will do the trick...

if (value.substr(-1) === "?") {
    // do what you need here
}

string.substr(x) will start at the character with index x and go to the end of the string. This is normally a positive number so "abcdef".substr(2) returns "cdef". If you use a negative number then it counts from the end of the string backwards. "abcdef".substr(-2) returns "ef".

string.substr(-1) just returns the last character of the string.

Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67
2

If you want a cute endsWith function:

String.prototype.endsWith = function(pattern) {
    var d = this.length - pattern.length;
    return d >= 0 && this.lastIndexOf(pattern) === d;
};

console.log('Is this a question ?'.endsWith('?')); // true

Took the answer here.

Community
  • 1
  • 1
Antoine Cloutier
  • 1,330
  • 11
  • 23
-1

You can use \?$ regex to find strings ending with ? mark.

var str = "what is your name?";
var patt = new RegExp("\? $");
if (patt.test(str))
{
      // do your stuff
}
Antony Francis
  • 304
  • 1
  • 7