Javascript Regular Expression - Quantifiers (Examples)

Tech:
Javascript
Since:
1 year ago
Views:
7

Quantifiers in Javascript Regular Expression is a way to match a pattern by specifying the number of times the pattern should be matched.

1: n+

It matches any string that contains at least one n.

var str = "Fallinfo Fallinfo";
var patt = /o+/g;
var x = str.match(patt);

// OUTPUT - o,o

2

var str = "Fallinfo Fallinfo";
var patt = /\w+/g;
var x = str.match(patt);

// OUTPUT - Fallinfo, Fallinfo;

3: n*

It matches any string that contains zero or more occurrences of n. It must have first character. It may have second character. It may have two or more second character.

var str = "Fallinfo";
var patt = /li*/g;
var x = str.match(patt);

// OUTPUT - l,li

4: n?

It matches any string that contains zero or one occurrences of n. It must have first character. It may have second character. It cannot have two or more second character.

var str = "1, 100 or 1000?";
var patt = /10?/g;
var x = str.match(patt);

// OUTPUT - 1,10,10

5: n{X}

It matches any string that contains a sequence of X n's.

var str = "100, 1000, 10000, 100000";
var patt = /\d{4}/g;
var x = str.match(patt);

// OUTPUT - 1000,1000,1000

6: n{X,Y}

It matches any string that contains a sequence of X to Y n's.

var str = "100, 1000, 10000, 100000";
var patt = /\d{3,4}/g;
var x = str.match(patt);

// OUTPUT - 100,1000,1000,1000

7: n{X,}

It matches any string that contains a sequence of at least X n's.

var str = "100, 1000, 10000, 100000";
var patt = /\d{3,}/g;
var x = str.match(patt);

// OUTPUT - 100,1000,10000,100000

8: n$

It matches any string with n at the end of it. If not found, it returns -1.

var str = "Fallinfo";
var patt = /fo$/g;
var x = str.search(patt);

// OUTPUT - 6

9: ^n

It matches any string with n at the beginning of it. If not found, it returns -1.

var str = "Fallinfo";
var patt = /^Fa/g;
var x = str.search(patt);

// OUTPUT - 0

10: ?=n

It matches any string that is followed by a specific string n. If not found, it returns -1.

var str = "Fallinfo Fallinfo";
var patt = /fo(?= Fa)/g;
var x = str.search(patt);

// OUTPUT - 6

11: ?!n

It matches any string that is not followed by a specific string n.

var str = "Fallinfo Fallinfo";
var patt = /fo(?! Fa)/g;
var x = str.search(patt);

// OUTPUT - 15