12

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?

Alexandru R
  • 8,024
  • 16
  • 59
  • 93
  • Just concatenate `p`, `"(\d{3,})"`, and `s` (escape `p` and `s` per http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex) – Slippery Pete Sep 03 '14 at 14:11

2 Answers2

26

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.

FrostyDog
  • 2,836
  • 1
  • 17
  • 18
Daryl Ginn
  • 1,336
  • 9
  • 14
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|*"]
anubhava
  • 713,503
  • 59
  • 514
  • 593