0

This almost has the answer... How do you use a variable in a regular expression?

I need to know if I can use variables instead of hardcode in the regex?

str1 = str1.replace(/abcdef/g, "stuvwxyz");

can I use variables instead of /abcdef/g and "stuvwxyz"

3 Answers 3

7

Of course that you can, every single bit of this can be dynamic:

var pattern = 'abcdef';
var input = 'stuvwxyz';
var modifiers = 'g';
var regex = new RegExp(pattern, modifiers);
var str1 = 'Hello abcdef';
str1 = str1.replace(regex, input);

Checkout the docs as well.

Sign up to request clarification or add additional context in comments.

5 Comments

Is there any reason to use new here?
@kennebec, you may checkout the following thread about the new keyword in javascript: stackoverflow.com/questions/383402/…
These answers are all just about the same (or were, you did some fast editing) but you were first.
Other answers don't mention how to make the regex dynamic, just the string to be searched and the what to replace it with.
@juan-mendes yes juan... that is why I said "or were" he edited really fast... he is good. His initial answer was just like the rest.
1

Yes.

var pattern = /abcdef/g;
var input = "stuvwxyz";
str1 = str1.replace(pattern, input);

Comments

1

Like this?

var regex = /abcdef/g;
var string = "stuvwxyz";
var str1 = "abcdef";
str1 = str1.replace(regex, string);

Comments

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.