Create a Regular Expression
// Regular Expression Literal
const regexObj = /^word$/
// Regular Expression Constructor
const regexObj = new RegExp("^word$");
Test & Replace
Test example
const regex = /^corn/;
regex.test('corncob')
true
regex.test('popcorn')
false
Replace example
const regex = /^corn/;
const string1 = 'corndog'
string1.replace(regex, 'hot')
'hotdog'
const string2 = 'popcorn'
string2.replace(regex, 'tart')
'popcorn'
Flags
i
Case-insensitiveg
Global; keeps searching for the regexm
Multiline; considers the line break a part of the word
Usage/regex/igm
Case-insensitive flag example
/lion/i.test('LION');
> true
'LION'.replace(/lion/i, 'mouse');
> "mouse"
Global flag example
'She ate a watermelon at the waterpark.'.replace(/water/, '');
> "She ate a melon at the waterpark."
'She ate a watermelon at the waterpark.'.replace(/water/g, '');
> "She ate a melon at the park."
Multiline flag example
const treat = `cheese
cheese
cheese`;
treat.replace(/^cheese$/, 'fruit');
cheese
cheese
cheese
treat.replace(/^cheese$/m, 'fruit');
fruit
cheese
cheese
treat.replace(/^cheese$/mg, 'fruit');
fruit
fruit
fruit