A regex question

i know we can hand write a regex and use it, but is it possible to write a regex indirectly? like let a function take each part of a string and put it in a regex expression then use it to match something later in the code?
like for example looping through a string letters and see if they have a match in a another string… ? this case comes up alot in codewars.
thank you.

Yes, you can define a reusable function.

There is the RegExp object, which offers much more flexibility in designing regex, such as interpolating variables in them.

You can do that with the help of RegEx object. Regex object take a string as first argument and any modifiers as second argument. Modifier like /g for global /i for insensitivity etc.
Second argument can be omitted if you don’t need any modifiers. So by defining any variable as RegEx and passing string into it. You will automatically get regex for that string.
e.g
const numbersOnly = new RegEx("[0-9]")
array.every( val => val.match(numbersOnly))

I’m about to go to sleep but i need a little clarification, can i loop through an array of strings puting each of them in the RegEx object as regexes ? Like use a function’s parameter in the parentheses of the RegEx object and let regexes be created one after the other?
Is this code below possible?

Let str = "abcdefg";
Function test(par){
  Let regy = new RegExp(par);
  Return regy.test(str);
}
Console.log(test('c'));


I’m sorry i can’t turn my laptop on and try it, because it’s late and i have to go to bed i have work tomorrow?
By the way is there a phone terminal? I searched for that but it got complicated.
Thank you.

I ran it on onecompiler.com and it worked, thank you.

1 Like

ofc you can. e.g
let str = “abcdef”
array.every( val => str.match(new RegEx(val)))

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.