0

I have a question related to formatting strings. User should parse a string in the Format XX:XX. if the string parsed by user is in the format XX:XX i need to return true, else false:

app.post('/test', (req, res) => {
   if (req.body.time is in the format of XX:XX) {
       return true
   } else {
       return false
   }
}); 
4
  • please add some use cases. Commented Jan 11, 2018 at 13:19
  • regular expressions. Commented Jan 11, 2018 at 13:20
  • Post the code that you attempted along with the issues in it. Commented Jan 11, 2018 at 13:20
  • On the server i would only accept the hh:mm format. It's the iso standard format and best for saving in databases and such. it's also what you get when you stringify a Date to json. The view is responsible to display it as the client pleases. One good thing that handle it is the time input that requires the format to be hh:mm but can display differently if they want to see 12h format. 24h is what you would always get if you post a form with a time input, even if it's displayed as 12h with am/pm Commented Jan 11, 2018 at 13:30

3 Answers 3

4

You can use the RegExp.test function for this kind of thing.

Here is an example:

var condition = /^[a-zA-Z]{2}:[a-zA-Z]{2}$/.test("XX:XX");
console.log("Condition: ", condition);

The regex that I've used in this case check if the string is composed from two upper or lower case letters fallowed by a colon and other two such letters.

Based on your edits it seems that you're trying to check if a string represents an hour and minute value, if that is the case, a regex like this will be more appropriate /^\d{2}:\d{2}$/. This regex checks if the string is composed of 2 numbers fallowed by a colon and another 2 numbers.

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

Comments

4

The tool you're looking for is called Regular Expressions.

It is globally supported in almost every development platform, which makes it extremely convenient to use.

I would recommend this website for working out your regular expressions.

/^[a-zA-Z]{2}:[a-zA-Z]{2}&/g is an example of a Regular Expression that will take any pattern of:

[a-zA-Z]{2} - two characters from the sets a-z and A-Z. Followed by : Followed by the same first argument. Essentially, validating the pattern XX:XX. Of course, you can manipulate it as to what you want to allow for X.

^ marks the beginning of a string and $ marks the end of it, so ASD:AS would not work even though it contains the described pattern.

Comments

1

try using regex

var str = "12:aa";
var patt = new RegExp("^([a-zA-Z]|[0-9]){2}:([a-zA-Z]|[0-9]){2}$");
var res = patt.test(str);
if(res){  //if true
 //do something
}
else{}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.