Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
14
rated 0 times [  18] [ 4]  / answers: 1 / hits: 19379  / 10 Years ago, wed, september 3, 2014, 12:00:00

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?


More From » regex

 Answers
33

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.


[#69576] Sunday, August 31, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brennonr

Total Points: 124
Total Questions: 101
Total Answers: 101

Location: Estonia
Member since Wed, Jun 8, 2022
2 Years ago
;