match string with regex code example
Example 1: javascript regex example match
//Declare Reg using slash
let reg = /abc/
//Declare using class, useful for buil a RegExp from a variable
reg = new RegExp('abc')
//Option you must know: i -> Not case sensitive, g -> match all the string
let str = 'Abc abc abc'
str.match(/abc/) //Array(1) ["abc"] match only the first and return
str.match(/abc/g) //Array(2) ["abc","abc"] match all
str.match(/abc/i) //Array(1) ["Abc"] not case sensitive
str.match(/abc/ig) //Array(3) ["Abc","abc","abc"]
//the equivalent with new RegExp is
str.match('abc', 'ig') //Array(3) ["Abc","abc","abc"]
Example 2: js string to regex
const regex = new RegExp('https:\\/\\/\\w*\\.\\w*.*', 'g');
Example 3: regex match exact string
you want to achieve a case insensitive match for the word "rocket"
surrounded by non-alphanumeric characters. A regex that would work would be:
\W*((?i)rocket(?-i))\W*
Example 4: match regex
const regex = /([a-z]*)ball/g;
const str = "basketball football baseball";
let result;
while((result = regex.exec(str)) !== null) {
console.log(result[1]);
// => basket
// => foot
// => base
}