How to use Regular Expression in Javascript
Author: Doe Hoon LEE
We will first look at some basic regular expression patterns!
# | Pattern | String |
---|---|---|
1 | DAVID | ‘DAVID’ |
2 | [DAVID] or D|A|V|I|D |
one of D, A, V, I, D |
3 | [^david] | without D, A, V, I, D |
4 | ^[DAVID] | starting with one of D, A, V, I, D |
5 | ^ | indicates string start |
6 | $ | indicates end of string |
7 | \d or [0-9] | number |
8 | {n} | n of |
9 | {n1,n2} | n1 ~ n2 |
Let’s try using these in real examples then!
const test1 = /DAVID/;
const test2_1 = /[DAVID]/;
const test2_2 = /D|A|V|I|D/;
const test3 = /[^DAVID]/;
const test4 = /^[DAVID]/;
const test_5_and_7_and_9 = /^[A-Z]{2}[0-9]{6}[A-Z]{2}/;
const string1 = "DAVID";
const string2 = "NOT DAVID";
const string3 = "APPLE";
const string4 = "PILL";
const string5 = "KR035720KS";
test1.test(string1); // => true
test2_1.test(string2); // => true
test2_2.test(string2); // => true
test3.test(string3); // => true
test4.test(string4); // => false
test_5_and_7_and_9.test(string5); // => true
Here are some fun techniques you can use with regex!
Remove consecutive/repeating pattern
// let str = "dd_aaa_vvvv_iiiii_dddddd";
return str.replace(/(.)\1+/g, "$1");
// => "d_a_v_i_d"
Cut every nth letters
// cut every single letter
"ABCDEFGHIJKLMNOPQRSTUVWXYZ".match(/.{1,1}/g);
// => ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
// cut every TWO letters
"ABCDEFGHIJKLMNOPQRSTUVWXYZ".match(/.{1,2}/g);
// => ["AB", "CD", "EF", "GH", "IJ", "KL", "MN", "OP", "QR", "ST", "UV", "WX", "YZ"]
Find alphabets only!
let str = "1A2BC3DEF4GDSAF84";
str.match(/[A-Z]+/g);
// => ["A", "BC", "DEF", "GDSAF"]
Find numbers only!
let str = "abc123";
let strTwo = "123";
/^\d+$/.test(str) // => false
/^\d+$/.test(strTwo) // => true
Leave a comment