mtlca401
mtlca401

Reputation: 23

javascript regular expressions with variable content

I have a working reg expression that does a replace function based on the expression. It works perfect. It finds a specific string based on the beginning of the string and the expression. This is it:

str.replace(/\bevent[0-9]*\=/, "event");

what this does is it changes event=1 to event.

What if event was a variable word? What if I needed to look for conference also?

I have tried:

var type = "conference";

str.replace(/\b/ + type+ /[0-9]*\=/, "conference");

and:

str.replace(/\b/type/[0-9]*\=/, "conference");

neither worked.

how can I pass a javascript string into a regular expression?

Upvotes: 2

Views: 1041

Answers (3)

Kyle
Kyle

Reputation: 22258

Create a new regex object with your variable.

read this...

http://www.w3schools.com/js/js_obj_regexp.asp

Upvotes: 0

Shad
Shad

Reputation: 15451

You can do that with the RegExp Object:

str.replace(RegExp('\b' + reStr + '[0-9]*\='),StrToReplaceWith)

Upvotes: 1

deceze
deceze

Reputation: 522081

Instead of writing a RegEx literal, use a string to create a new RegExp object:

str.replace(new RegExp('\b' + var + '[0-9]'), …)

Upvotes: 2

Related Questions