Ativ
Ativ

Reputation: 429

Javascript regex - specific number of characters in unordered string

I'm trying to test whether or not an unordered string has '3' in it 5 times.

For example:

var re = /3{5}/;
re.test("333334"); //returns true as expected
re.test("334333"); //returns false since there is no chain of 5 3s

What regex would make the second line return true? If regex is not the best way to test this, what is?

Thanks!

Upvotes: 5

Views: 186

Answers (4)

Lucas T.
Lucas T.

Reputation: 406

I would go with:

string.indexOf('33333') > -1

Upvotes: 0

Oriol
Oriol

Reputation: 288130

Try

(str.match(/3/g) || []).length >= 5

Or

str.split(3).length > 5

Where str is the string you want to test.

Upvotes: 6

bbonev
bbonev

Reputation: 1438

I would go for

s.replace(/[^3]/,'').length >= 5

Assuming that the string to be tested is named s

Upvotes: 2

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

You can write this:

var re = /(?:3[^3]*){5}/;

Upvotes: 3

Related Questions