Regular expressions in javascript
./code/regular_expression.js
1/*
2/^HTML/ Matches the letters HTML at the start of a string
3
4/^HTML/i Matches the letters HTML (ignore cases) at the start of a string
5
6*/
7
8// /[0-9][0-9]*/ Match a non-zero digit, followed by any \# of digits
9//
10// /\bjavascript\b/i Match "javascript" as a word, case-insensitive
11
12console.log(/^HTML/.test("HTML ABC")); // true
13console.log(/^HTML/.test("Html ABC")); // false
14console.log(/^HTML/i.test("Html ABC")); // true, ignore cases
15
16console.log(/[0-9][0-9]*/.test("0")); // true
17console.log(/[0-9][0-9]*/.test("01234")); // true
18
19console.log(/\bjavascript\b/i.test("hello javascript")); // true
20console.log(/\bjavascript\b/i.test("hello_javascript")); // false
21
22let text = "testing: 1, 2, 3"
23let pattern = /\d+/g // matches all instances of one or more digits
24
25console.log(pattern.test(text)); // true, a match exists
26
27// return the first matched position
28console.log(text.search(pattern)); // 9
29console.log(text.match(pattern)); // ['1', '2', '3'], array of all matches
30console.log(text.replace(pattern, '#')); // testing: #, #, #
31
32console.log(text.split(/\D+/)) // split on non-digit, ['', '1', '2', '3']