2

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?

3 Answers 3

2

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

str.replace(new RegExp('\b' + var + '[0-9]'), …)
Sign up to request clarification or add additional context in comments.

1 Comment

I guess its kind of messed up that I can only pick one answer, but your answer worked perfectly. I did have to take out the '\b' though. That didn't work for some reason.
1

You can do that with the RegExp Object:

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

2 Comments

I took your answer because it fit exactly what I was looking for. Is it strange that the '\b' would not work? I had to take it out.
I'm afraid I don't have much experience with the word boundary character =(
0

Create a new regex object with your variable.

read this...

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

1 Comment

Ok. This still answers his question.

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.