Regex Example

by zynh0722

JavaScript

//  *   : match 0 or more of previous character
//  +    : match 1 or more of previous character
// {x}   : match x of the previous character
// {x,}  : match x or more of the previous character
// {x,y} : match between x or y of the previous character

let string = 'I like books but I also like oatmeal served on a board';

// The g at the end of the literal makes .match return all matches
// and not just the first one and is called the 'global' flag

console.log( string.match(/o+/g) ); // This logs ['oo', 'o', 'o', 'o']
console.log( string.match(/o{2}/g) ); // This logs ['oo']

console.log( string.match(/bo*/g) ); // This logs ['boo', 'b', 'bo']
console.log( string.match(/bo+/g) ); // This logs ['boo', 'bo']

string = 'book bookookook bookook boo';

console.log( string.match(/b(ook)+/g) ); // This logs ['book', 'bookookook', 'bookook']