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()

Comment and share

1. Usage of Unicode Character

“I hear and I forget. I see and I remember. I do and I understand.”

1
2
var rate = 3
"★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate);

2. An efficient way to handle JavaScript exception

1
2
3
4
5
6
7
8
// by 'Jordan Hall'
try {
//something
} catch (e) {
window.location.href =
"http://stackoverflow.com/search?q=[js]+" +
e.message;
}

3. Locate all DOM elements visually

1
2
3
4
5
6
7
8
// by 'Addy Osmani' https://addyosmani.com/
[].forEach.call($$("*"),function(a){
a.style.outline="1px solid #"+(~~(Math.random()*(1<<24))).toString(16)
})
Array.prototype.forEach.call(document.querySelectorAll('*'),
dom => dom.style.outline = `1px solid #${parseInt(Math.random() *
Math.pow(2,24)).toString(16)}`)

4. Separate number with ,

1
2
3
4
var test1 = '1234567890'
var format = test1.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
console.log(format) //Output: 1,234,567,890

5. An unofficial way to do deep clone for JSON object

1
2
3
4
5
var a = {
a: 1,
b: { c: 1, d: 2 }
}
var b=JSON.parse(JSON.stringify(a))

6. Implicitly convert string to number

1
2
var a =1
+a

7. Usage of ES6 Spread Operator

1
2
3
4
5
// quickly remove duplicated number
[...new Set([2, "2", 3, 3, 4, 1])] //output: [2, "2", 3, 4, 1]
// create an array with length 3 and all number 2
Array(3).fill(2) //outpput: [2, 2, 2]

8. Find Max and Min use Math

1
2
3
var numbers = [-99, 0 , 99 , 98 , -1];
var maxNum = Math.max.apply(Math, numbers); // output: 99
var minNum = Math.min.apply(Math, numbers); // ouput: -99

9. Debugging tips

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// eye candy for JSON view
var fruits = [
{ fruit: 'Tangerine', weight: 43 },
{ fruit: 'Cherry', weight: 13 },
{ fruit: 'Litchi', weight: 25 }
];
console.table(fruits);
// output code snippets execution time period
console.time('Timer01');
var items = [];
for(var i = 0; i < 100000; i++){
items.push({index: i});
}
console.timeEnd('Timer01');

10. Remove Timers from Global Scope

1
2
3
4
var highestTimeoutId = setTimeout(";");
for(var i=0; i<hightestTimeoutId; i++){
clearTimeout(i);
}

Comment and share

“The world and your career are unpredictable, so you are better off learning subjects of permanent value” - Gian-Carlo Rota

fetch() is a global method provided by Fetch API which can be used to GET or POST data asynchronously through the network.

GET

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fetch("url", {
method: "GET",
mode: 'cors'
}
// default method is 'GET' if not provided
// add "mode: 'cors'" to send cross orign request
).then(
response => response.json()
// methed json() will convert the ReadableStream to json data format
).then(
data => console.log('Json data retrieved:', data)
// data is ready for use
);
// you can also use methods below to extract a body
// arrayBuffer(), blob(), text(), formData()

POST

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var dataToServer = {....};
fetch("url", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(dataToServer)
}
// set headers as needed
).then(
response => response.text()
// response from server
).then(
result => console.log('Result content:', result)
).catch(
err => console.log('error meesage', err.messge)
);

Difference between fetch() and jQuery.ajax()

From Fetch API:

The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
By default, fetch won’t send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set).

Comment and share

  • page 1 of 1
Author's picture

Zhao Cai

What will your verse be?


Web developer


Toronto