1

How do I dynamically Assign a pattern?

I've tried:

var str = "hebbbbllo";
var patt = new RegExp;
patt =("b", "g");
console.log(str.match(patt).length);

But the code produces an error:

Uncaught TypeError: Cannot read property 'length' of null

I've also tried to use the pattern "/b/g" but it also doesn't work

1 Answer 1

2

You should do this:

var patt = new RegExp("pattern","flags");

So, do this:

var str = "hebbbbllo";
var patt = new RegExp("b","g");
console.log(str.match(patt).length);

Read more about it at MDN

Update:

If you want to do it in your way, you can do:

var str = "hebbbbllo";
var patt = RegExp;
var regex = patt("b", "g");    
console.log(str.match(regex).length);
Sign up to request clarification or add additional context in comments.

1 Comment

but i said i want to assign it dynamically, after i'm declaring the variable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.