|
18 | 18 | * 1. exec(): Tests for matches in a string. This returns the first match.
|
19 | 19 | * 2. test(): Tests for matches in a string. This returns true or false.
|
20 | 20 | */
|
| 21 | + |
| 22 | +// The following are five regexes that developers often use. |
| 23 | + |
| 24 | +// 1. Any Numeric Characters |
| 25 | +const numeric = /\d+/; |
| 26 | +numeric.test('123444'); // returns true |
| 27 | +numeric.test('333ass'); // returns true |
| 28 | +numeric.test('5asdasd'); // returns true |
| 29 | +numeric.test('asdasd'); // returns false |
| 30 | + |
| 31 | +// 2. Only Numeric Characters |
| 32 | +const onlyNumeric = /^\d+$/; |
| 33 | +onlyNumeric.test('123'); // true |
| 34 | +onlyNumeric.test('123a'); // false |
| 35 | +onlyNumeric.test('a'); // false |
| 36 | + |
| 37 | +// 3. Floating Numeric Characters |
| 38 | +const floatNumeric = /^[0-9]*.[0-9]*[1-9]+$/; |
| 39 | + |
| 40 | +floatNumeric.test('12'); // true |
| 41 | +floatNumeric.test('1'); // false |
| 42 | +floatNumeric.test('12.3'); // true |
| 43 | + |
| 44 | +// 4. Only Alpha Numeric Characters |
| 45 | +const alphaNumeric = /[a-zA-Z0-9]/; |
| 46 | +alphaNumeric.test('somethingELSE'); // true |
| 47 | +alphaNumeric.test('hello'); // true |
| 48 | +alphaNumeric.test('112a'); // true |
| 49 | +alphaNumeric.test('112'); // true |
| 50 | +alphaNumeric.test('^'); // false |
| 51 | + |
| 52 | +// 5. Query String |
| 53 | + |
| 54 | +const url = 'http://your.domain/product.aspx?category=4&product_id=2140&query=lcd+tv'; |
| 55 | +let queryString = {}; |
| 56 | +url.replace(new RegExp('([^?=&]+)(=([^&]*))?', 'g'), function ($0, $1, $2, $3) { |
| 57 | + queryString[$1] = $3; |
| 58 | +}); |
| 59 | +console.log(queryString); |
| 60 | + |
| 61 | +// http://your.domain/product.aspx: undefined, category: '4', product_id: '2140', query: 'lcd+tv' |
0 commit comments