tags:

views:

47

answers:

1

I want to detect two versions of the same thing, plural and now

eg:

"piece" and "pieces" should both return a match.

var re_1 = new RegExp("how many piece", "i");

or

var re_1 = new RegExp("how many pieces", "i");

How do I form a RegExp expression in Javascript to detect both singular and plural in the same pattern?

+1  A: 
>>> /how many pieces?/.test('how many piece')
true
>>> /how many pieces?/.test('how many pieces')
true
>>> /how many pieces?/.test('how many piecez')
true
>>> /how many pieces?/.test('how many piec')
false

The question mark denotes that the prior character is optional. You shouldn't need to construct a new RegExp unless you're dynamically generating it, feel free to add any additional options after the end / ( g for global, i for case insensitive ).

meder
I see. Thank you very much :)
Rohan
This wouldn't work very well for words that need "es" instead of just "s" (box->boxes) as well as y->ies (delivery->deliveries), and countless other examples.
Artem Russakovskii