Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically create regex to use in .match Javascript? [duplicate]

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?

like image 253
Alexandru R Avatar asked Sep 03 '14 14:09

Alexandru R


1 Answers

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.

like image 105
Daryl Ginn Avatar answered Nov 01 '22 08:11

Daryl Ginn