-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 .

3
  • 1
    What have you tried to solve your problem? FYI, it has nothing to do with jQuery. Commented Jun 30, 2014 at 11:39
  • And what about languages like Spanish, where it seems a question should be preceded by '¿' as well as succeeded by '?' Commented Jun 30, 2014 at 11:42
  • I dont keep this question downvoted then , delete it Commented Jul 2, 2014 at 5:11

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

can you add little explanation how substr() will work in thid case
Thanks for the explanation @Archer, better put it in answer
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.

Comments

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

1 Comment

This code throws Uncaught SyntaxError: Invalid regular expression: /? $/: Nothing to repeat

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.