Kegan Quimby
Kegan Quimby

Reputation: 546

jQuery/JavaScript regex to match any three first characters followed by an exact string

I need a regular expression to validate a form, based on the value of a drop down. The value, however, is randomly generated by PHP (but is always a 2 digit number).

It needs to be valid for "38|One Evening" The number 38 is what's going to change. So far, I have

//return value of dropdown
var priceOption = $("#price_option-4").val();

//make sure it ends with "One Evening"
var oneEvening = priceOption.match(/^ * + 'One Evening' $/);

Which I thought would match any string as long as it's followed by "one evening"

Upvotes: 0

Views: 2838

Answers (5)

Paul Alan Taylor
Paul Alan Taylor

Reputation: 10680

/^.+?One Evening$/

Breaking it down

// ^ starts with
// . any character
// + quantifier - one or more of preceding character
// ? non-greedy - ensure regex stops at One Evening.
// One Evening = literal text
// $ match end of string.

Note that my answer reflects the requirement to match any sequence of characters, then One Evening.

I think you may be better off being more specific and ensuring you definitely have two numeric characters.

Upvotes: 0

Bruno
Bruno

Reputation: 5822

If you can it is best to be specific. Try the following:

// <start of string> <2 digits> <|One Evening> <end of string>
/^\d{2}\|One Evening$/.test( priceOption );

Upvotes: -1

gdoron
gdoron

Reputation: 150253

strings are not to be use with regex, you should just write what you want to match\test inside the regex literal, without the quotes.

   /^\d{2}\|One Evening$/.test(priceOption);
//  ^^^^^^                          Begins with two digits
//        ^^                        Escaped the | meta char.
//          ^^^^^^^^^^^^            Then until the end: One Evening    

Upvotes: 6

A. Wolff
A. Wolff

Reputation: 74420

For xx|One Evening

/^\d{2}\|One Evening$/

Upvotes: 1

Ωmega
Ωmega

Reputation: 43673

Simply use

/^\d\d\|One Evening$/.test(priceOption);

Upvotes: 1

Related Questions