18

I need to dynamically create a regex to use in match function javascript. How would that be possible?

var p = "*|";
var s = "|*";
"*|1387461375|* hello *|sfa|* *|3135145|* test".match(/"p"(\d{3,})"s"/g)

this would be the right regex: /\*\|(\d{3,})\|\*/g

even if I add backslashes to p and s it doesn't work. Is it possible?

1

2 Answers 2

34

RegExp is your friend:

var p = "\\*\\|", s = "\\|\\*"

var reg = new RegExp(p + '(\\d{3,})' + s, 'g')

"*|1387461375|* hello *|sfa|* *|3135145|* test".match(reg)

The key to making the dynamic regex global is to transform it into a RegExp object, and pass 'g' in as the second argument.

Working example.

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

5 Comments

beat me to it by about 15 seconds :). It ends up as a bad regex, but it matches what the op asked
Although the new operator isn't required when creating instances of built-in objects, it's still recommended.
SyntaxError: Invalid regular expression: /*|(d{3,})|*/: Nothing to repeat. I also tried escaping p and s without success
@AlexandruRada Edited. When using RegExp, you need to double escape.
right, I was only escaping and wasn't working.
0

You can construct a RegExp object using your variables first. Also remember to escape * and | while forming RegExp object:

var p = "*|";
var s = "|*";
var re = new RegExp(p.replace(/([*|])/g, '\\$1')
                 + "(\\d{3,})" + 
                 s.replace(/([*|])/g, '\\$1'), "g");

var m = "*|1387461375|* hello *|sfa|* *|3135145|* test".match(re);
console.log(m);

//=> ["*|1387461375|*", "*|3135145|*"]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.