Regular Expression (Regex) is a search pattern, which can be used to find or replace certain text in strings.

Test Cases

Case 1 | Find

1
2
3
4
5
6
7
8
9
var testStringA = "This is a test string";
/* 'g' means global which means to return all matched text in the string */
/* 'i' means to ignore the case */
/* check if string contains 'test' */
var regexPatternA = /test/gi;
// output: 1
var textCountA = testStringA.match(regexPatternA).length;

Case 2 | Find

1
2
3
4
5
6
7
8
var testStringB = "This is a test string...";
/* '\' is used to ignore special character */
/* check if string contains '.' */
var regexPatternB = /\./gi;
// output: 3
var textCountB = testStringB.match(regexPatternB).length;

Case 3 | Find

1
2
3
4
5
6
7
8
9
10
11
12
var testStringC = "This is a test string with number 12345 ...";
/* '\d+', '\d' means to match digits, '+' means to match one or more digits */
/* check if string contains '.' */
var regexPatternC1 = /\d+/gi;
var regexPatternC2 = /\d/gi; // var regexPatternC2 = /[1-9]/gi;
// output: 1 | ['12345']
var textCountC1 = testStringC.match(regexPatternC1).length;
// output: 5 | ['1', '2', '3', '4', '5']
var textCountC2 = testStringC.match(regexPatternC2).length;

Case 4 | Replace

1
2
3
4
5
6
7
var testString = "This is a test string for function xxx ";
/* match text 'xxx' */
var regexPattern = /xxx/gi;
var newstring = testString.replace(regexPattern, 'Replace');
console.log(newstring); // This is a test string for function Replace

Case 5 | Test

1
2
3
4
5
6
7
8
9
10
// The Regex test() method will return true or false when match a certain string
var regexNumTest = /\d/g; // test if string contains digits
var regexStartTest = /^[A-Z]/g; // test if string start with any word from A-Z
var regexEndTest = /[0-9]$/g; // test if string end with any digits from 0-9
var testString = "This is a test string for function test";
regexNumTest.test(testString); // false
regexStartTest.test(testString); // true
regexEndTest.test(testString); // false

Resource

Regex Cheatsheet
MDN - Regualr Expressions
MDN - Regex Test
MDN - String.prototype.replace()