How to dynamically create regex to use in .match Javascript?
This question already has an answer here:
RegExp is your friend:
var p = "*|", s = "|*"
var reg = new RegExp(p + '(d{3,})' + s, 'g')
"*|1387461375|* hello *|sfa|* *|3135145|* test".match(reg)
Working example.
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|*"]
链接地址: http://www.djcxy.com/p/76832.html