4

I have a question regarding creating a regex from a string. The code is in javascript, basically a variable gets a string. I am not sure how to convert the string to the regex. Here is the code

  var string = "the code";
  var regex = /(the |code )/g;

How can I convert my string to regex using javascript?

3
  • You want to extract the pattern from the string? Commented Oct 8, 2015 at 17:14
  • What are you going to do with the regexp once you have it? Commented Oct 8, 2015 at 17:42
  • I feel you are looking for hole word matching. I'd use /\b(?:the|code)\b/g. Then, var myRegex = new RegExp('\\b(?:' + str.replace(/ /g,'|') + ')\\b','g');. Or a more universal: var myRegex = new RegExp('(^|\\W)(?:' + str.replace(/ /g,'|') + ')(?!\\w)','g');. Commented Oct 8, 2015 at 20:02

3 Answers 3

7

use RegExp:

var stringRe = "the code";
var re = new RegExp(stringRe, "g");
Sign up to request clarification or add additional context in comments.

Comments

2

Using the RegExp constructor, like this:

var regex = new RegExp(str, 'g');

1 Comment

The OP may or may not know how to use the RegExp constructor, but it seems pretty clear he wants to create a regexp to look for any of the words in the string.
0

Try something like this:

var str = "the code";
var myRegex = new RegExp('(' + str.replace(' ','|') + ')','g');

5 Comments

myRegex is /(the|code)/g - not what is expected.
What do the parentheses do?
@stribizhev, good point. I was just giving him a way to create the regex he specified in his question.
no need for parenthesis here
@vstepaniuk, please see my comment immediately above yours.

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.