1.21 gigawatts
1.21 gigawatts

Reputation: 17770

Creating a dynamic RegExp pattern to include a variable value

I have a RegExp that I would like to make dynamic and create in a string. I want to change this:

var result:Object = value.match(/John\/(.*?) /);

to this:

var firstName:String = "John";
var result:Object = value.match(firstName + "\/(.*?) "); // this doesn't work

I'm using ActionScript but I think what would work in JavaScript would work as well here.

Upvotes: 0

Views: 164

Answers (1)

Matt Zeunert
Matt Zeunert

Reputation: 16561

In Javascript you can create a new instance of the RegExp class:

var firstName:String = "John";
var result:Object = value.match(new RegExp(firstName + "\/(.*?) "));

When you use value.match(firstName + "\/(.*?) "); the first parameter to the match function is a string, but it should be a regular expression object.

Upvotes: 1

Related Questions