How to dynamically create regex to use in .match Javascript?

This question already has an answer here:

  • How do you use a variable in a regular expression? 16 answers

  • 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

    上一篇: 在javascript中使用正则表达式中的变量

    下一篇: 如何动态创建正则表达式以在.match Javascript中使用?