This is all about fundamentals of implementing regular expression
.(wildcard) represents single character
/foo.bar/
.*represents any number of characters
/foo.*bar/
\srepresents white space,*represents any number of characters
/foo\s*bar/
[abc]represents character class -> inclusion list
/[fcl]oo/
[^abc]represents except character class -> exclusion list
/[^fcl]oo/
[a-c]represents character class range -> inclusion list
/[a-c]oo/
[a-c]represents character class range -> inclusion list
/[a-cyz]oo/
[a-c]represents character class range -> inclusion list
/[a-cA-Cyz]oo/
[a-c]represents character outside class range -> exclusion list
/[^a-c]oo/escaping with backslash
/x*\.y*/if a period is inside char class, no need to use backslash
/x[.#*]y/since
^or\inside char class has different meaning we need to use backslash to exclude
/x[.#*\^\\]y/
^represents beginning fo a line
/^foo.*/
$represents end of a line
/.*bar$//^foo$//^[0-9]{3}$//^[a-z]{3,6}$//(ha){4,}/
^and$are used so that regex don't break the string and treat it as whole
/^(ha){1,4}$/
a+considers 1 or more occurances of a, whilea*considers 0 or more repetations
/fooa+bar/
?checks only 1 or 0 occurances of preceeding char
/https?\/\// new RegExp(`https?//`)pipe symbol
|resembles or operator
/(log|ply)wood/anything wrapped by capture group will be available in the array value
gwill search for every match, if absent only first match is considered
input string: 'I have 1024x720 & 123x456 monitor'
expected output: "I have '1024px by 720px' & '123px by 456px' monitor"
re = /([0-9]+)x([0-9]+)/g input.replace(re, (...arg) => `'${arg[1]}px by ${arg[2]}px'`) // get all the matches input.match(re) // ["1024x720", "123x456"]input string: 'Sourav Modak'
expected output: Modak, Sourav
re = /([a-zA-z]+)\s([a-zA-z]+)/g input.replace(re, (...arg) => `${arg[2]}, ${arg[1]}`)input string: "It's 8:32 in morning"
expected output: "It's 32 mins past 8 in morning"
re = /(1[0-2]|[0-9]):([1-5][0-9])/g input.replace(re, (...args) => `${args[2]} mins past ${args[1]}`) input.match(re) // ["8:32"] re.exec(input) // ["8:32", "8", "32"]input string: "123-456-7890"
expected output: "xxx-xxx-7890"
re = /^([1-9][0-9]{2})-([0-9]{3})-([0-9]{4})$/ input.replace(re, (...args) => `xxx-xxx-${args[3]}`)js re.exec(input) // ["123-456-7890", "123", "456", "7890"]input string: "Jan 30th 1982" / "Jan 5th 1982"
expected output: "30-Jan-82" / "Jan 5th 1982"
re = /([a-zA-Z]{3})\s([1-2]?[0-9]|3?[0-1])[a-z]{2}\s[0-9]{2}([0-9]{2})/ input.replace(re, (...args) => `${args[2]}-${args[1]}-${args[3]}`)