Javascript Regular Expression - Brackets (Examples)

Tech:
Javascript
Since:
2 years ago
Views:
6

In regular expressions, sometimes you need to use brackets to group parts of the expression. Here are some examples of how to use brackets.

Type 1: [abc]

To find any character between the brackets.

var str = "Fallinfo";
var patt = /[fi]/g;
var str = x.match(patt);

// OUTPUT - i,f

// [abcde..] - Any character between the brackets
// [A-Z] - Any character from uppercase A to uppercase Z
// [a-z] - Any character from lowercase a to lowercase z
// [A-z ]- Any character from uppercase A to lowercase z

Type 2: [^abc]

To find any character NOT between the brackets.

var str = "Fallinfo";
var patt = /[^F]/g;
var x = str.match(patt);

// OUTPUT - a,l,l,i,n,f,o

// [abcde..] - Any character between the brackets
// [A-Z] - Any character from uppercase A to uppercase Z
// [a-z] - Any character from lowercase a to lowercase z
// [A-z ]- Any character from uppercase A to lowercase z

Type 3: [0-9]

To find any character between the brackets (any digit).

var str = "123456789";
var patt = /[1-4]/g;
var x = str.match(patt);

// OUTPUT - 1, 2, 3, 4;

Type 4: [^0-9]

To find any character NOT between the brackets (any non-digit).

var str = "123456789";
var patt = /[^1-4]/g;
var x = str.match(patt);

// OUTPUT - 5, 6, 7, 8, 9;

Type 5: (x|y)

To find any of the alternatives specified.

var str = "Fallinfo 123";
var patt = /(fo|i|2)/g;
var x = str.match(patt);

// OUTPUT - i, fo, 2;